正向和反向查询
正向 ----> 关联字段在当前表中,从当前表向外查叫正向
反向 —> 关联字段不在当前表中,当当前表向外查叫反向
正向通过字段,反向通过表名查

<>一对一 OneToOneField
# 一个文章详情表一对一关联文章表,相当于Foreignkey 加unique class Article(models.Model): nid =
models.AutoField(primary_key=True) desc = models.CharField(max_length=255) class
ArticleDetail(models.Model): """ 文章详情表 """ nid = models.AutoField(primary_key=
True) content = models.TextField() article = models.OneToOneField(to="Article",
to_field="nid",on_delete=models.DO_NOTHING)
正向:

1、基于对象:obj.(外键).属性
ArticleDetail_obj = models.ArticleDetail.objects.filter(pk=pk).first()
ArticleDetail_obj.article.desc
2、基于字段跨表查询:外键__属性
models.ArticleDetail.objects.filter(pk=2).values("article__desc")
反向:从详情查文章

1、基于对象:obj.(表名小写).属性
article_obj = models.Article.objects.filter(pk=pk).first() article_obj.
articledetail.content
2、基于字段跨表查询:表名小写__属性
models.Article.objects.filter(id=1).values('articledetail__content')
<>一对多 ForeignKey

book – > publish :一个出版社有多个书
class Publish(models.Model): nid = models.AutoField(primary_key=True) name=
models.CharField( max_length=32) class Book(models.Model): nid = models.
AutoField(primary_key=True) title = models.CharField( max_length=32) #
与Publish建立一对多的关系 publish=models.ForeignKey(to="Publish",to_field="nid",on_delete
=models.CASCADE)
正向:

1、基于字段:obj.(外键).属性
book_obj = models.Book.objects.filter(title='红楼梦').first() book_obj.publish.
name
反向:obj.(表名小写_set).all()
1、set查询
publish_obj=models.Publish.objects.filter(name="教育").first() books =
publish_obj.book_set.all() for book in books: print(book.title)
<>多对多 ManyToManyField
class Author(models.Model): nid = models.AutoField(primary_key=True) name=
models.CharField( max_length=32) age=models.IntegerField() #
与AuthorDetail建立一对一的关系 authorDetail=models.OneToOneField(to="AuthorDetail",
on_delete=models.CASCADE) class Author(models.Model): nid = models.AutoField(
primary_key=True) name=models.CharField( max_length=32) age=models.IntegerField(
) class Book(models.Model): nid = models.AutoField(primary_key=True) title =
models.CharField(max_length=32) #
与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表 authors=models.
ManyToManyField(to='Author',)
正向:

1、基于字段:obj.(外键).all()
book_obj = models.Book.objects.filter(title="python教程").first() authors =
book_obj.authors.all() for author in authors: print(author.name,author.age)
反向:obj.(表名小写_set).all()
1、set查询
author_obj = models.Author.objects.filter(name="moke").first() books =
author_obj.book_set.all() for book in books: print(book.title)
2、related_name查询
author_obj.related_name.all()

技术
下载桌面版
GitHub
Gitee
SourceForge
百度网盘(提取码:draw)
云服务器优惠
华为云优惠券
腾讯云优惠券
阿里云优惠券
Vultr优惠券
站点信息
问题反馈
邮箱:[email protected]
吐槽一下
QQ群:766591547
关注微信