Many-to-one
创建模型
from django.db import models class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField() def __str__(self):
return "%s %s" % (self.first_name, self.last_name) class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self):
return self.headline class Meta:
ordering = ('headline',)
数据迁移
#生成迁移文件,记录下在models.py文件中的改动
python manage.py makemigrations ##将改动的内容作用于数据库,生成相应的数据
python manage.py migrate
表操作
创建数据
>>> #创建几个记者
>>> r = Reporter(first_name='John', last_name='Smith', email='john@example.com')
>>> r.save() >>> r2 = Reporter(first_name='Paul', last_name='Jones', email='paul@example.com')
>>> r2.save() >>> #创建一篇文章
>>> from datetime import date
>>> a = Article(id=None, headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
>>> a.save() >>> a.reporter.id
1 >>> a.reporter
<Reporter: John Smith> >>> #通过Reporter对象创建文章
>>> new_article = r.article_set.create(headline="John's second story", pub_date=date(2005, 7, 29))
>>> new_article
<Article: John's second story>
>>> new_article.reporter
<Reporter: John Smith>
>>> new_article.reporter.id
1
查询方法
>>>#反向查询,过滤出 Article 中以 'This' 开头的 headline
>>>r.article_set.filter(headline__startswith='This')
<QuerySet [<Article: This is a test>]> >>># 查询 Articles 中关联对象 Reporter 的 first name 是 "John" 的所有文章,这里是完全匹配 (first name = "John")
>>> Article.objects.filter(reporter__first_name='John')
<QuerySet [<Article: John's second story>, <Article: This is a test>]> >>>#查询两次相关字段, 这将转换为WHERE子句中的AND条件
>>> Article.objects.filter(reporter__first_name='John', reporter__last_name='Smith')
<QuerySet [<Article: John's second story>, <Article: This is a test>]> >>>#对于关联查找,可以提供主键值或显式传递关联对象
>>> Article.objects.filter(reporter__pk=1)
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
>>> Article.objects.filter(reporter=1)
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
>>> Article.objects.filter(reporter=r)
<QuerySet [<Article: John's second story>, <Article: This is a test>]> >>> # __in
>>> Article.objects.filter(reporter__in=[1,2]).distinct()
<QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
>>> Article.objects.filter(reporter__in=[r,r2]).distinct()
<QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]> >>>#还可以使用查询集作为查询条件
>>>Article.objects.filter(reporter__in=Reporter.objects.filter(first_name='John')).distinct()
<QuerySet [<Article: John's second story>, <Article: This is a test>]> >>>#反向查询,以关联对象 Article 作为条件获取满足条件的 Reporter
>>> Reporter.objects.filter(article__pk=1)
<QuerySet [<Reporter: John Smith>]>
>>> Reporter.objects.filter(article=1)
<QuerySet [<Reporter: John Smith>]>
>>> Reporter.objects.filter(article=a)
<QuerySet [<Reporter: John Smith>]> >>> Reporter.objects.filter(article__headline__startswith='This')
<QuerySet [<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]>
>>> Reporter.objects.filter(article__headline__startswith='This').distinct()
<QuerySet [<Reporter: John Smith>]> >>> #计数 count()
>>>Reporter.objects.filter(article__headline__startswith='This').count()
3 >>> #去重后计数
>>>Reporter.objects.filter(article__headline__startswith='This').distinct().count()
1
转移数据---add(obj)
>>>#创建一篇新文章
>>> new_article2 = Article.objects.create(headline="Paul's story", pub_date=date(2006, 1, 17), reporter=r)
>>> new_article2.reporter
<Reporter: John Smith>
>>> new_article2.reporter.id
1
>>> r.article_set.all()
<QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]> >>> #将new_article2文章转移到 r2 ,r 与这篇文章就没有关联了
>>> r2.article_set.add(new_article2)
>>> new_article2.reporter.id
2
>>> new_article2.reporter
<Reporter: Paul Jones> >>> r.article_set.all()
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
>>> r2.article_set.all()
<QuerySet [<Article: Paul's story>]> >>> r.article_set.count()
2 >>> r2.article_set.count()
1
删除数据---delete()
>>>#可以先获取 Reporter 后再删除
>>> Article.objects.all()
<QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
>>> Reporter.objects.order_by('first_name')
<QuerySet [<Reporter: John Smith>, <Reporter: Paul Jones>]>
>>> r2.delete()
>>> Article.objects.all()
<QuerySet [<Article: John's second story>, <Article: This is a test>]>
>>> Reporter.objects.order_by('first_name')
<QuerySet [<Reporter: John Smith>]> >>>#可以在查询中使用联接 delete() 直接删除:
>>>Reporter.objects.filter(article__headline__startswith='This').delete()
>>> Reporter.objects.all()
<QuerySet []>
>>> Article.objects.all()
<QuerySet []>
学习自用,欢迎大神评论、指正
详情见Django文档:
https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_one/
随机推荐
- Web之localStorage
localStorage: 1.localStorage拓展了cookie的4K限制 2.localStorage会可以将第一次请求的数据直接存储到本地,这个相当于一个5M大小的针对于前端页面的数据库 ...
- 2017浙江工业大学-校赛决赛 小M和天平
Description 小M想知道某件物品的重量,但是摆在他面前的只有一个天平(没有游标)和一堆石子,石子可以放左边也可以放右边.他现在知道每个石子的重量.问能不能根据上述条件,能不能测出所问的重量. ...
- Codeforces 371BB. Fox Dividing Cheese
Two little greedy bears have found two pieces of cheese in the forest of weight a and b grams, corre ...
- Linux 环境下安装 Nginx+php+mysql 开发环境
一直以来都没有养成记录学习的好习惯,我想从这么一天开始,把自己学习和工作中的经验和坑都记录下来.等到以后老的时候还有可以回忆的地方. 最近在学习linux,虽然已经玩linux很久了,但是没有怎么用心 ...
- 连接sql server、插入数据、从数据库获取时间(C#)
using System; using System.Data.SqlClient; namespace Test { //连接数据库 public class Connection { privat ...
- Springboot2.X集成Quartz集群
为什么要使用Quzrtz集群 在项目进行集群部署时,如果业务在执行中存在互斥关系,没有对定时任务进行统一管理,就会引起业务的多次执行,不能满足业务要求.这时就需要对任务进行管理,要保证一笔业务在所有的 ...
- Todolist总结
一.组件类里面的函数尽可能写成箭头函数的形式,方便绑定this 上面的箭头函数是好的,写面的不好,他需要在用的时候绑定this,或者在constructor绑定,如下: 如上用的时候绑定this是不好 ...
- 关于搭建系统直播和Thinkphp的杂谈(持续更新)
Q:Access denied for user 'root'@'localhost' 错误 A:第一种:配置文件中把数据库的用户名密码再改一遍,把runtime里的文件删除 第二种:修改syste ...
- docker 配置国内镜像源 linux/mac/windows
部分内容来自:http://guide.daocloud.io/dcs/daocloud-9153151.html 加速器官方DaoCloud承诺:加速器服务永久免费且无流量限制 使用前提:注册Dao ...
- codevs 1146 ISBN号码
时间限制: 1 s 空间限制: 128000 KB 题目等级 : 白银 Silver 题目描述 Description 每一本正式出版的图书都有一个ISBN号码与之对应,ISBN码包括9位数字.1 ...