该文档描述了在使用一对多或是多对多关系时,在 manager 中可用的方法。该文档使用下面两个案例:
- 一个是以 ForeignKey 关联的一对多关系:
class Reporter(models.Model):
...
class Article(models.Model):
reporter = models.ForeignKey(Reporter)
在上面这个例子当中,下面所提及的方法都包含在 reporter.article_set 这个 manager 当中。
- 另一个例子则是以 ManyToManyField 关联的多对多关系:
class Topping(models.Model):
...
class Pizza(models.Model):
toppings = models.ManyToManyField(Topping)
在这个例子中,下面所提及的方法都包含在 topping.pizza_set 和 pizza.toppings 两个 manager 中。
QuerySet.add(obj1[, obj2, ...])
添加指定的 model 对象到关联对象集中。
例如:
>>> b = Blog.objects.get(id=1)
>>> e = Entry.objects.get(id=234)
>>> b.entry_set.add(e) # Associates Entry e with Blog b.
QuerySet.create(**kwargs)
创建一个新对象并保存,然后将其添加到关联对象集中,并返回这个新对象:
>>> b = Blog.objects.get(id=1)
>>> e = b.entry_set.create(
... headline='Hello',
... body_text='Hi',
... pub_date=datetime.date(2005, 1, 1)
... )
# No need to call e.save() at this point -- it's already been saved.
这基本上等价于(下面所列的稍稍有点简单):
>>> b = Blog.objects.get(id=1)
>>> e = Entry(
.... blog=b,
.... headline='Hello',
.... body_text='Hi',
.... pub_date=datetime.date(2005, 1, 1)
.... )
>>> e.save(force_insert=True)
要注意:没必要对定义关系的 model 指定关键字参数。在上面的例子当中,我们并没有将 blog 做为参数传给 create() 方法。Django 会将新的 Entry 对象中 blog 字段设置为 b。
QuerySet.remove(obj1[, obj2, ...])
从关联对象集中移除指定的对象:
>>> b = Blog.objects.get(id=1)
>>> e = Entry.objects.get(id=234)
>>> b.entry_set.remove(e) # Disassociates Entry e from Blog b.
为了避免出现数据不一致的情况出现,这个方法仅对指定了 null=True 的 ForeignKey 外键对象有用。如果关联字段并没有设置 None (NULL),那么对象就不能从关系中被删除。在上面的例子中,将 e 对象从 b.entry_set() 中删除,就相当于令 e.blog = None,如果 blog ForeignKey 不允许 null=True,那么上面的操作就无法进行。
QuerySet.clear()
从关联对象集中清空所有对象:
>>> b = Blog.objects.get(id=1)
>>> b.entry_set.clear()
要注意并不是删除关联的对象,仅仅是将他们从关系中剥离。
和 remove() 一样, clear() 也仅仅在 ForeignKey 上可用,并且要求字段的 null=True。