创建模型

在本例中,Place 和 Restaurant 为一对一关系

from django.db import models

class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80) def __str__(self):
return "%s the place" % self.name class Restaurant(models.Model):
place = models.OneToOneField(
Place,
on_delete=models.CASCADE,
primary_key=True,
)
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False) def __str__(self):
return "%s the restaurant" % self.place.name class Waiter(models.Model):
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
name = models.CharField(max_length=50) def __str__(self):
return "%s the waiter at %s" % (self.name, self.restaurant)

数据迁移

#生成迁移文件,记录下在models.py文件中的改动
python manage.py makemigrations ##将改动的内容作用于数据库,生成相应的数据
python manage.py migrate

表操作

创建数据

>>> #创建几个地点
>>> p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
>>> p1.save()
>>> p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
>>> p2.save() >>> #创建一家餐厅
>>>r=Restaurant(place=p1,serves_hot_dogs=True,
serves_pizza=False)
>>> r.save() >>>#Restaurant 可以访问 Place
>>> r.place
<Place: Demon Dogs the place> >>>#Place 可以访问 Restaurant
>>> p1.restaurant
<Restaurant: Demon Dogs the restaurant> >>>#P2没有关联餐厅 可以通过捕获异常,避免出错
>>> from django.core.exceptions import ObjectDoesNotExist
>>> try:
>>> p2.restaurant
>>> except ObjectDoesNotExist:
>>> print("There is no restaurant here.")
There is no restaurant here. >>>#也可以通过 hasattr() 获取是否有某个属性来判断
>>> hasattr(p2, 'restaurant')
False >>>#使用赋值符号设置place 。因为Place是restaurant的主键,所以保存将创建一个新的restaurant,将之前的restaurant
>>> r.place = p2
>>> r.save()
>>> p2.restaurant
<Restaurant: Ace Hardware the restaurant>
>>> r.place
<Place: Ace Hardware the place> >>>#再次设置place,在反向使用赋值:
>>> p1.restaurant = r
>>> p1.restaurant
<Restaurant: Demon Dogs the restaurant>

查询数据

>>>#all()只返回餐馆,而不是地方。注意有两个餐馆, Ace硬件餐厅是在对r.place=p2的调用中创建的

>>> Restaurant.objects.all()
<QuerySet [<Restaurant: Demon Dogs the restaurant>, <Restaurant: Ace Hardware the restaurant>]> >>>#all()返回所有位置,不管它们是否有餐馆
>>> Place.objects.order_by('name')
<QuerySet [<Place: Ace Hardware the place>, <Place: Demon Dogs the place>]> >>>#可以使用跨关系查找
>>> Restaurant.objects.get(place=p1)
<Restaurant: Demon Dogs the restaurant>
>>> Restaurant.objects.get(place__pk=1)
<Restaurant: Demon Dogs the restaurant>
>>> Restaurant.objects.filter(place__name__startswith="Demon")
<QuerySet [<Restaurant: Demon Dogs the restaurant>]>
>>> Restaurant.objects.exclude(place__address__contains="Ashland")
<QuerySet [<Restaurant: Demon Dogs the restaurant>]> >>>#反向查找也是可以的
>>> Place.objects.get(pk=1)
<Place: Demon Dogs the place>
>>> Place.objects.get(restaurant__place=p1)
<Place: Demon Dogs the place>
>>> Place.objects.get(restaurant=r)
<Place: Demon Dogs the place>
>>> Place.objects.get(restaurant__place__name__startswith="Demon")
<Place: Demon Dogs the place> >>>#在餐厅里加一个waiter
>>> w = r.waiter_set.create(name='Joe')
>>> w
<Waiter: Joe the waiter at Demon Dogs the restaurant> >>>#访问服务员
>>> Waiter.objects.filter(restaurant__place=p1)
<QuerySet [<Waiter: Joe the waiter at Demon Dogs the restaurant>]>
>>> Waiter.objects.filter(restaurant__place__name__startswith="Demon")
<QuerySet [<Waiter: Joe the waiter at Demon Dogs the restaurant>]>

随机推荐

  1. [題解](最小生成樹/LCA)luogu_P1967貨車運輸

    一道好題不出所料又抄的題解 1.首先對於這張圖肯定要考慮走哪些邊不走哪些邊,發現我們想要的肯定那些邊權最大的邊,所以想到最大生成樹 這樣能保證選到盡量大的邊 2.跑完最大生成樹后每兩點之間就有唯一路徑 ...

  2. vue教程1-初体验

    起步 var vm = new Vue({ // 选项 }) #每个Vue应用都需要通过实例化Vue来实现,语法格式继承原生js <!DOCTYPE html> <html lang ...

  3. Django 使用Paginator分页

    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger subclass_s = models.subclas ...

  4. Mysql优化配置

    Mysql配置优化 一.环境介绍 Mysql版本:5.5.27 二.优化内容 字段 介绍 推荐值 skip-locking 避免MySQL的外部锁定,减少出错几率增强稳定性 back_log MySQ ...

  5. java面试题(基础部分)

    1.一个".java"源文件中是否可以包括多个类(不是内部类)?有什么限制? 可以有多个类,但只能有一个public的类,并且public的类名必须与文件名相一致. 2.Java有 ...

  6. [问题解决]Deepin环境变量设置无效解决

    将环境变量的设置放在这里:  gedit ~/.bashrc 详见参考: linux下如何设置环境变量PATH : http://blog.csdn.net/witsmakemen/article/d ...

  7. .NET Core 1.0 CentOS7 尝试(三、使用VSCode创建一个Web应用)

    参考地址:https://docs.asp.net/en/latest/tutorials/your-first-mac-aspnet.html 一.使用VSCode创建一个目录FirstWebApp ...

  8. Vue实例的4个常用选项

    1.过滤器 filters:在不改变的data的情况下输出前端页面需要的格式数据.例如将小数过滤为整数等.filters是一个对象,里边定义一个function方法,function传入一个参数,fu ...

  9. Azure Powershell blob中指定的vhd创建虚拟机

    #此脚本用于 Azure 存储账户中已有 vhd 镜像文件创建虚拟机,一般用于做好镜像测试 #----------------------------------------------------- ...

  10. git的基本使用命令操作

    Linux操作命令行:    mkdir - 创建文件夹,    cd - 切换文件路径    pwd - 显示文件路径    ls -ah - 可以查看隐藏的文件夹名(.git)    cat 文件 ...