Many-to-one
阿新 • • 發佈:2019-01-14
建立模型
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',)
View Code
資料遷移
#生成遷移檔案,記錄下在models.py檔案中的改動
python manage.py makemigrations
##將改動的內容作用於資料庫,生成相應的資料
python manage.py migrate
表操作
建立資料
>>> #建立幾個記者
>>> r = Reporter(first_name='John', last_name='Smith', email='[email protected]')
>>> r.save()
>>> r2 = Reporter(first_name='Paul', last_name='Jones', email='[email protected]')
>>> 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
View Code
查詢方法
>>>#反向查詢,過濾出 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
View Code
轉移資料---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
View Code
刪除資料---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 []>
View Code
學習自用,歡迎大神評論、指正
詳情見Django文件:
https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_one/