我赞美你品格高尚,崇敬你洁白无瑕。我爱你、想你、盼你,像对每一个季节那样。我爱你、想你、盼你,不管世俗的偏见怎样厉害。冬――四季之一的冬,你来吧!我喜欢你纯净的身躯,喜欢你严厉的性格,我要在你的怀抱中锻炼、奋斗、成熟……你可以和春天的万花,夏天的麦浪,秋天的瓜果……比美!
先设定一个关系模型如下:
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的互相读取方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。