欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

django 外键model的互相读取方法

程序员文章站 2022-06-08 21:57:55
先设定一个关系模型如下: from django.db import models class blog(models.model): name = mod...

先设定一个关系模型如下:

from django.db import models
class blog(models.model):
 name = models.charfield(max_length=100)
 tagline = models.textfield()
 def __str__(self):   
  return self.name
 
class author(models.model):
 name = models.charfield(max_length=50)
 email = models.emailfield()
 def __str__(self):   
  return self.name
 
class entry(models.model):
 blog = models.foreignkey(blog)
 headline = models.charfield(max_length=255)
 body_text = models.textfield()
 authors = models.manytomanyfield(author)
 def __str__(self):   
  return self.headline

上面的数据关系很明晰,entry中有blog和author的外键,如果要在entry中读取blog和author的数据很容易:

entry = entry.objects.all()
for e in entry:
 blog = e.blog
 author = e.authors

要在blog和author中读取entry也可以:

blog = blog.objects.all()
entry = blog.entry_set.all()
 
author = author.objects.all()
entry = author.entry_set.all()

下面通过entry使blog和author互相读取,比如要知道一个blog的author只需如下:

blogs = blog.objects.all()
for blog in blogs:
 if blog.name== “我们想要查询的博客的name”
  author = blog. entry_set.authors

要查询一个author的所有blog如下:

authors = author.objects.all()
blogs = []
 
for author in authors:
 if author.name== “我们想要查询的author的name”
  for entry in author.entry_set.all():
   blogs.append(entry. blog)

以上这篇django 外键model的互相读取方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。