创建模型

在本例中,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. 统计最长回文串(传说中的Manacher算法)Hihocoder 1032

    算法的核心就在这一句上了:p[i] = min(p[2*id-i], p[id] + id - i); #include <iostream> #include <cstdio> ...

  2. Day2课后作业:三级菜单简单版

    menu = { '北京':{ '海淀':{ '五道口':{ 'soho':{}, '网易':{}, '谷歌':{} }, '中关村':{ '爱奇艺':{}, '汽车之家':{}, 'youku':{ ...

  3. java.lang.IllegalArgumentException: Illegal character in query at index ...解决办法

    今天在写智能机器人问答实现的时候遇到了一个问题,就是我发送消息不能输入空格 给我报了一个错误java.lang.IllegalArgumentException: Illegal character ...

  4. 第十二章 设计用户界面 之 设计自适应的UI布局

    1. 概述 随着手机和平板设备的日益普及,使得开发者不得不考虑MVC网站在移动设备上的展示. 本章内容包括:运行在多种设备上的程序(屏幕分辨率,CSS,HTML).设计手机端Web程序. 2. 主要内 ...

  5. PLSQL连接Oracle64监听和服务的配置!

    前言: 这里不会涉及到太多关于版本问题的解决,只是简单提一下基本的监听和服务配置问题的解决,让你可以快速的用PLSQL连接上你自己创建的Oracle数据库(这里示例数据库名为ORCL); 版本问题: ...

  6. 88E1111

    千兆网phy芯片 支持GMII,RGMII,MII等接口 具备4个GMII时钟模式 支持自适应功能 超低功耗模式 功率降低模式 MDC/MDIO/TWSI接口 支持10Mb/s,100Mb/s,100 ...

  7. Windows64+Python27下配置matplotlib

    注:转载请注明原作者并附上原文链接! 网上看了很多方法,均遇到这样或者那样的问题导致安装失败,最后自己摸索一条方法,最终安装成功了. 1,首先安装numpy,这个可以选择install安装包,很简单, ...

  8. Openjudge 2.5 6264:走出迷宫

    总时间限制:  1000ms 内存限制:  65536kB 描述 当你站在一个迷宫里的时候,往往会被错综复杂的道路弄得失去方向感,如果你能得到迷宫地图,事情就会变得非常简单. 假设你已经得到了一个n* ...

  9. mysql 存在更新,不存在插入

    String sql = "insert into wb_result " + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? ...

  10. CSAPP lab1 datalab-handout

    这是一个关于机器级的整数.浮点数表示和位运算的实验.要求用给定的操作符.尽可能少的操作数去实现对应的函数功能. 完整的实验包:链接: https://pan.baidu.com/s/1xUBi3XDl ...