057:表关系之一对多

表关系:
表之间的关系都是通过外键来进行关联的。而表之间的关系,无非就是三种关系:一对一、一对多(多对一)、多对多等。以下将讨论一下三种关系的应用场景及其实现方式。

一对多:
1. 应用场景:比如文章和作者之间的关系。一个文章只能由一个作者编写,但是一个作者可以写多篇文章。文章和作者之间的关系就是典型的多对一的关系。
2. 实现方式:一对多或者多对一,都是通过 ForeignKey 来实现的。还是以文章和作者的案例进行讲解。

models.py:

class Category(models.Model):
    username = models.CharField(max_length=128)
    def __str__(self):
        return "<Category: name:%s>" % self.username

class Article(models.Model):
    title = models.CharField(max_length=128)
    content = models.TextField()
    category = models.ForeignKey("Category", on_delete=models.CASCADE)
    # category = models.ForeignKey("Category", on_delete=models.CASCADE, related_name='articles')
    # user = models.ForeignKey('cms.user',on_delete=models.CASCADE, null=True)
    def __str__(self):
        return "<Article: title:%s, content:%s>" % (self.title, self.content)

views.py:

def index(request):
   # 第一种添加文章数据方式
    # category = Category(username="张三")
    # category.save()
    #
    # article = Article(title='1111', content='fuck you')
    # article.category = category
    # article.save()
    # print(article.category.username)
    # article.category.username = '李四'
    # print(article.category.username)
   # 获取某类下的所有文章
    category = Category.objects.get(pk=2)
    aritcles = category.article_set.all()      # 谁引用了表的字段作为外键,就设置这个 "模型的_set" 方法获取数据            
    # aritcles = category.articles.all()                    #如果模型中设置了: related_name='articles'
   for article in aritcles: 
    print(article)

   # 第二种添加文章数据方式
    article1 = Article(title='xyz', content="778899")
    category.article_set.add(article1,bulk=False)
    # category.articles.add(article1,bulk=False)            #如果模型中设置了: related_name='articles'
   return HttpResponse('success')
posted @ 2019-12-28 14:42  小明911  阅读(223)  评论(0编辑  收藏  举报