创建模型

在本例中,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. FONT 字体颜色大全

    用这句代码 替换 AmericanTypewriter-Bold字段就会有不同的字体样式 _typeLabel.font = [UIFont fontWithName:]; Font Family: ...

  2. python使用C扩展

    CPython还为开发者实现了一个有趣的特性,使用Python可以轻松调用C代码 开发者有三种方法可以在自己的Python代码中来调用C编写的函数-ctypes,SWIG,Python/C API.每 ...

  3. axios 访问和返回拦截,token处理,返回异常统一处理

    在axios文件夹中,index.js添加拦截 访问拦截: import store from '../store' axios.interceptors.request.use( config =& ...

  4. 我的NopCommerce之旅(2): 系统环境及技术分析

    一.系统环境 IIS7.0 or above ASP.NET 4.5(MVC 5.0) .NET Framework 4.5.1 or above VS 2012 or above 二.架构设计 Pl ...

  5. 利用自定义消息处理函数的WPARAM或LPARAM参数传递指针

    有自定义消息: #define WM_TEST WM_USER+121 消息处理函数: afx_msg void OnTest(WPARAM wParam,LPARAM lParam); 该消息是一个 ...

  6. 一次性删除数据库所有表和所有存储过程 SQL语句

    一次性删除数据库所有表和所有存储过程 SQL语句 今天转移数据库数据,需要把数据库原来的表和存储过程清空.删除所有的表:如果由于外键约束删除table失败,则先删除所有约束: --/第1步****** ...

  7. C#语言 数据类型 类型转换

    数据类型有  基本数据类型 和  引用数据类型 两大类型. 数据类型 C#语言 .NET(通用语言) 大小(字节) 值区间 基本数据类型 值类型 整型 不能存在小数点,可以有负数 byte Byte ...

  8. .NET 通过 NPOI 操作 Excel

    目录 .NET 通过 NPOI 操作 Excel 第一步:通过 NuGet 获取 NPOI 包并引入程序集 第二步:引入 NPOI 帮助类 第三步:在程序中调用相应的方法对数据进行导出导入操作 将 D ...

  9. HDU 1171 Big Event in HDU 杭电大事件(母函数,有限物品)

    题意: 分家问题,对每种家具都估个值,给出同样价值的家具有多少个,要求尽可能平分,打印的第一个数要大于等于第二个数. 思路: 可以用背包做,也可以用母函数.母函数的实现只需要注意一个点,就是每次以一种 ...

  10. codevs 1487 大批整数排序(水题日常)

     时间限制: 3 s  空间限制: 16000 KB  题目等级 : 黄金 Gold 题目描述 Description !!!CodeVS开发者有话说: codevs自从换了评测机,新评测机的内存计算 ...