关系如下
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()