创建模型

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/

随机推荐

  1. 大数加法 HDU 1002

    #include <iostream> #include <cstring> #include <string> #include <cstdio> # ...

  2. (洛谷P2512||bzoj1045) [HAOI2008]糖果传递 || 洛谷P4016 负载平衡问题 || UVA11300 Spreading the Wealth || (洛谷P3156||bzoj3293) [CQOI2011]分金币

    bzoj1045 洛谷P4016 洛谷P2512 bzoj3293 洛谷P3156 题解:https://www.luogu.org/blog/LittleRewriter/solution-p251 ...

  3. 【aspnetcore】异常捕捉可用知识点

    1.使用过滤器ExceptionFilter:补充:常用过滤器:AuthorizationFilter.ActionFilter.ResultFilter.ResourceFilter.Excepti ...

  4. mac Latex dvipdfm 缺少字体错误 Failed to read UCS2/UCS4 TrueType cmap

    dvipdfmx 命令产生 ** ERROR ** Failed to read UCS2/UCS4 TrueType cmap... 错误的原因是没有把 simsun.ttf simkai.ttf ...

  5. BundleConfig包含js,css失败

    今天在做mvc项目的时候,引入了bootstrap样式.但是包含css和js的时候出错了 于是我查阅资料,好多人都说后缀名前面不能包含".",于是我把min前面的".&q ...

  6. Mysql->order by SQL 根据多个条件排序

    Mysql中根据多个条件排序:(各个条件间使用逗号隔开)   首先根据class_name字符串长短升序排列,然后根据开始时间降序排列: SELECT * FROM signup_class s OR ...

  7. CF1081E Missing Numbers

    思路: 贪心乱搞. 实现: #include <bits/stdc++.h> using namespace std; typedef long long ll; const ll m = ...

  8. RStudio的Markdown

    Title This is an R Markdown document. Markdown is a simple formatting syntax for authoring web pages ...

  9. LinuxShell(脚本如何编译问题)

    想学shell的同学请记住: 如果你写好脚本后不给脚本执行权限那也是不行的: 添加执行权限: chmod +x 脚本名.sh 在Linux shell中有一个脚本编译命令: bash -v 脚本名.s ...

  10. 基于Python的Web应用开发实战——3 模板

    要想开发出易于维护的程序,关键在于编写形式简洁且结构良好的代码. 当目前为止,你看到的示例都太简单,无法说明这一点,但Flask视图函数的两个完全独立的作用却被融合在了一起,这就产生了一个问题. 视图 ...