创建模型

在本例中,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. [题解](约数)BZOJ_1053_反素数

    三条引理:1.1~N中最大风反质数,就是1~N中约数个数最多的最小的一个 比较显然,是应该看出来的一条 2.1~N中任何数的不同因子都不会超过10个,且所有质因子的指数之和不超过30: 2*3*5*7 ...

  2. BZOJ1108(思路)

    题目本质:因为只能往南和往东走所以不管怎么组合方案结果都是一样的Orz……我太菜了想不到嘤嘤嘤 #pragma comment(linker, "/STACK:1024000000,1024 ...

  3. POJ1470 LCA (Targan离线)

    bryce1010模板 http://poj.org/problem?id=1470 /*伪代码 Tarjan(u)//marge和find为并查集合并函数和查找函数 { for each(u,v) ...

  4. SNMP消息传输机制

    1.引言 基于TCP/IP的网络管理包含3个组成部分: 1) 一个管理信息库MIB(Management Information Base).管理信息库包含所有代理进程的所有可被查询和修改的参数.RF ...

  5. mybatis(错误) 项目启动时报“Result Maps collection already contains value forxxx”的解决方案

    使用逆向工程生成代码时,一定要将原来的代码删除干净,如果覆盖的话,不是真正的覆盖,在原来的代码上增加重复的代码,导致出错

  6. 遍历list集合的三种方式

    List<String> list1 = new ArrayList<String>(); list1.add("1"); list1.add(" ...

  7. watir-webdriver使用过程中异常

    1.在jruby版本1.6.7中,报异常:not such file to load --watir-webdriver 解决方法 :在文件的首行添加:require 'rubygems'       ...

  8. 国内的Jquery CDN免费服务

    Jquery是个非常流行的JS前端框架,在很多网站都能看到它的身影.很多网站都喜欢采用一些Jquery CDN加速服务,这样网站加载jquery会更快.之前火端网络的一些网站都是使用Google的jq ...

  9. java.lang.ClassCastException android.widget.RelativeLayout LayoutParams 异常

    1.在xml布局文件如下所示: <RelativeLayout android:layout_width="match_parent" android:layout_heig ...

  10. COGS 696. [IOI1996][USACO 2.3] 最长前缀

    ★   输入文件:prefix.in   输出文件:prefix.out   简单对比时间限制:1 s   内存限制:128 MB 描述 USACO 2.3.1 IOI96 在生物学中,一些生物的结构 ...