One-to-one
创建模型
在本例中,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>]>
随机推荐
- 20180607pip install xxx报错SyntaxError invalid syntax
用pip安装时都要在cmd命令行里启动的,而在python中无法运行.退出python运行环境就再执行pip可以了.而且最好用管理员身份运行cmdC:\WINDOWS\system32>cd D ...
- python入门之正则表达式
正则 通过re模块实现 eg:>>>import re >>>re.findall('abc',str_name) 在strname里面完全匹配字符串 ...
- 云服务中IaaS、PaaS、SaaS的区别
越来越多的软件,开始采用云服务. 云服务只是一个统称,可以分成三大类. IaaS:基础设施服务,Infrastructure-as-a-service PaaS:平台服务,Platform-as-a- ...
- 详解JS作用域(一)
一.什么是作用域 存储和访问变量,是任何一种编程语言最基本的功能之一,变量存在哪里?程序需要时如何找到它?这些问题需要一套良好的规则来规范,这套规则,就成为作用域. 二.编译原理 js通常归类为解释语 ...
- split()分割字符串用法
<script type="text/javascript"> var str="How are you doing today?" documen ...
- mysql合服 更新相同的用户名前追加服务器编号
表结构: CREATE TABLE IF NOT EXISTS `user` ( `) NOT NULL COMMENT '主键', `user_level` ) COMMENT '等级', `) C ...
- 《高性能JavaScript》 实用指南
By XFE-堪玉 阅读<高性能javascript>后,对其内容的一个整理和精简 加载与执行 将script标签放在body结尾标签上面 控制script标签数量(每一次script解析 ...
- Android 检查内存溢出
工具网址:https://github.com/square/leakcanary 中文版说明地址:http://www.liaohuqiu.net/cn/posts/leak-canary-read ...
- No input file specified的解决方法
(一)IIS Noinput file specified 方法一:改PHP.ini中的doc_root行,打开ini文件注释掉此行,然后重启IIS 方法二:请修改php.ini找到; cgi.for ...
- Grace Huang 2017/1/11
原文 This actress becomes each character she plays Grace Huang has no interested in doing same thing y ...