class RelatedManager
"關聯管理器"是在一對多或者多對多的關聯上下文中使用的管理器。它存在於下面兩種情況:
ForeignKey關系的“另一邊”。像這樣:
from django.db import models class Reporter(models.Model): # ... pass class Article(models.Model): reporter = models.ForeignKey(Reporter)
在上面的例子中,管理器reporter.article_set擁有下面的方法。
ManyToManyField關系的兩邊:
class Topping(models.Model): # ... pass class Pizza(models.Model): toppings = models.ManyToManyField(Topping)
這個例子中,topping.pizza_set 和pizza.toppings都擁有下面的方法。
add(obj1[, obj2, ...])
把指定的模型對象添加到關聯對象集中。 例如: >>> b = Blog.objects.get(id=1) >>> e = Entry.objects.get(id=234) >>> b.entry_set.add(e) # Associates Entry e with Blog b. 在上面的例子中,對於ForeignKey關系,e.save()由關聯管理器調用,執行更新操作。然而,在多對多關系中使用add()並不會調用任何 save()方法,而是由QuerySet.bulk_create()創建關系。 延伸: # 1 *[]的使用 >>> book_obj = Book.objects.get(id=1) >>> author_list = Author.objects.filter(id__gt=2) >>> book_obj.authors.add(*author_list) # 2 直接綁定主鍵 book_obj.authors.add(*[1,3]) # 將id=1和id=3的作者對象添加到這本書的作者集合中 # 應用: 添加或者編輯時,提交作者信息時可以用到.
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) 要注意我們並不需要指定模型中用於定義關系的關鍵詞參數。在上面的例子中,我們並沒有傳入blog參數給create()。Django會明白新的 Entry對象blog 應該添加到b中。
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. 對於ForeignKey對象,這個方法僅在null=True時存在。
clear()
從關聯對象集中移除一切對象。 >>> b = Blog.objects.get(id=1) >>> b.entry_set.clear() 注意這樣不會刪除對象 —— 只會刪除他們之間的關聯。 就像 remove() 方法一樣,clear()只能在 null=True的ForeignKey上被調用。
set()方法
先清空,在設置,編輯書籍時即可用到
注意
對於所有類型的關聯字段,add()、create()、remove()和clear(),set()都會馬上更新數據庫。換句話說,在關聯的任何一端,都不需要再調用save()方法。
直接賦值:
通過賦值一個新的可迭代的對象,關聯對象集可以被整體替換掉。
>>> new_list = [obj1, obj2, obj3] >>> e.related_set = new_list
如果外鍵關系滿足null=True,關聯管理器會在添加new_list中的內容之前,首先調用clear()方法來解除關聯集中一切已存在對象的關聯。否則, new_list中的對象會在已存在的關聯的基礎上被添加。