關(guān)系 多對多
# 文章會發(fā)布在多個媒體上
# 媒體也會發(fā)布多個文章
class Publication(models.Model):
title = models.CharField(max_length=30)
class Article(models.Model):
headline = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication)
# 使用add方法之前a1需要save,存在于數(shù)據(jù)庫中
a1.publications.add(p1)
# 創(chuàng)建一個新的媒體同時加入到發(fā)布媒體列表中
new_publication = a1.publications.create(title='Highlights for Children')
a1.publications.all()
p1.article_set.all()
# 正向
Article.objects.filter(publications__id=1)
Article.objects.filter(publications=1)
Article.objects.filter(publications=p1)
Article.objects.filter(publications__in=[1,2]).distinct()
Article.objects.filter(publications__in=[p1,p2]).distinct()
Article.objects.filter(publications__title__startswith="Science")
# 逆向
Publication.objects.filter(article__id=1)
Publication.objects.filter(article=1)
Publication.objects.filter(article=a1)
Publication.objects.filter(article__in=[1,2]).distinct()
Publication.objects.filter(article__in=[a1,a2]).distinct()
p2.article_set.add(a4)
new_article = p2.article_set.create(headline='Oxygen-free diet works wonders')
關(guān)系 多對一
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
new_article = r.article_set.create(headline="John's second story", pub_date=date(2005, 7, 29))
r.article_set.add(new_article2)
# 正向
Article.objects.filter(reporter=r)
# 逆向
Reporter.objects.filter(article=a)
關(guān)系 一對一
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
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)
class Waiter(models.Model):
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
# 正向
r.place
# 逆向
p1.restaurant
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。