Models and Databases 11.例子

2021-03-12  本文已影响0人  xncode

关系 多对多

# 文章会发布在多个媒体上
# 媒体也会发布多个文章

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,存在于数据库中
a1.publications.add(p1)
# 创建一个新的媒体同时加入到发布媒体列表中
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')

关系 多对一

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)

关系 一对一

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
上一篇下一篇

猜你喜欢

热点阅读