圆月山庄资源网 Design By www.vgjia.com

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

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的互相读取方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

标签:
django,model,读取

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com