django-表关系之一对多

在modele.py中,创建两个orm模型

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=100)

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    #使用ForeignKey创建外键
    #models.CASCADE -> 当Category表中的某个数据被删除,那么Article表中的对应的数据也会删除(级联删除)
    category = models.ForeignKey('Category',on_delete=models.CASCADE)

    #null=True -> 这个值为空的是因为之前已经插入过数据,为空的话可以不用强制插入数据
    author = models.ForeignKey('frontuser.FrontUser',on_delete=models.CASCADE,null=True)

使用下面这两条命令映射这两个ORM模型到数据库

python manage.py makemigrations

python manage.py migrate

-----------------------------------

在views.py中关联,并且通过这个关联并且查询数据

from .models import Category,Article
from django.http import HttpResponse

def one_to_many_view(request):
    """1.一对多的关联操作
    article = Article(title='钢铁是怎样炼成的',content='abc')
    category = Category.objects.first()     #获得数据库中Category该表下的数据
    author = FrontUser.objects.first()      #获得数据库中FrontUser该表下的数据

    article.category = category     #关联起来  这个 article是多   category 是 一
    article.author = author         # 同上关联起来

    article.save()      #保存

    return HttpResponse('关联success')
    """
    # 2.获取某个分类下的文章
    category = Category.objects.first()
    print(category.name)
    #获取articl下的第一条文章数据
    # article = category.article_set.first()  #因为关联上了,就可以从category表下通过article_set找到article表下的第一条数据
    # print(article)

    #获取article下的所有的文章数据
    articles = category.article_set.all()
    for article in articles:
        print(article)
    return HttpResponse('查询成功!')

更改django查询的默认方法:

这个  article_set  是django内置的查询数据的方法,也就是你的 表名称_set 形成的

我们可以更改这个方法

在models.py中

外键增加一个 related_name='articles'  ,这个articles就是你命名的方法名字,注意:article_set这个方法就不存在了

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    #使用ForeignKey创建外键
    #models.CASCADE -> 当Category表中的某个数据被删除,那么Article表中的对应的数据也会删除(级联删除)
    category = models.ForeignKey('Category',on_delete=models.CASCADE,related_name='articles')

在views.py中使用这个方法即可:  也就是将article_set 名称改为了  articles

def one_to_many_view(request):
    articles = category.articles.all()
    for article in articles:
        print(article)
    return HttpResponse('查询成功!')

 往表中添加数据并且保存的方法:

在views.py中

def one_to_many_view(request):
    article = Article(title='aaa',content='AAA')
    category.article_set.add(article,bulk=False)    #bulk=False添加并且自动保存数据
    return HttpResponse('查询成功!')

#注意,前提是Article表下的其他外键字段是可以为空的,不然报错,也就是null=True

猜你喜欢

转载自www.cnblogs.com/ifdashui/p/11891876.html
今日推荐