1、ForeignKey
情况I:
from django.db import models class Blog(models.Model):
pass class Entry(models.Model):
blog = models.ForeignKey(Blog)
访问方式:
b = Blog.objects.get(id=1)
b.entry_set.all()
情况II:
from django.db import models class Blog(models.Model):
pass class Entry(models.Model):
blog = models.ForeignKey(
Blog,
related_name='entries'
)
访问方式:
b = Blog.objects.get(id=1)
b.entries.all()
2、ManyToMany
情况I:
class Person(models.Model):
name = models.CharField(max_length=128) def __str__(self): # __unicode__ on Python 2
return self.name class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person) def __str__(self): # __unicode__ on Python 2
return self.name
访问方法:
>>> beatles = Group.objects.create(name="The Beatles")
>>> beatles.members.all()
<QuerySet [<Person: Ringo Starr>]>
>>> ringo = Person.objects.create(name="Ringo Starr")
>>> ringo.group_set.all()
<QuerySet [<Group: The Beatles>]>
情况II:
class Person(models.Model):
name = models.CharField(max_length=128) def __str__(self): # __unicode__ on Python 2
return self.name class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, related_name='groups') def __str__(self): # __unicode__ on Python 2
return self.name
访问方法:
>>> beatles = Group.objects.create(name="The Beatles")
>>> beatles.members.all()
<QuerySet [<Person: Ringo Starr>]> >>> ringo = Person.objects.create(name="Ringo Starr")
>>> ringo.groups.all()
<QuerySet [<Group: The Beatles>]>