ManyToManyField
class RelatedManager
"關聯管理器"是在一對多或者多對多的關聯上下文中使用的管理器。
它存在於下面兩種情況:
- 外鍵關系的反向查詢
- 多對多關聯關系
簡單來說就是當 點后面的對象 可能存在多個的時候就可以使用以下的方法
create()
創建一個新的對象,保存對象,並將它添加到關聯對象集之中,返回新創建的對象。
import datetime models.Author.objects.first().book_set.create(title="番茄物語", publish_date=datetime.date.today())
add()
把指定的model對象添加到關聯對象集中。
添加對象
author_objs = models.Author.objects.filter(id__lt=3)
models.Book.objects.first().authors.add(*author_objs)
添加id
models.Book.objects.first().authors.add(*[1, 2])
set()
更新model對象的關聯對象。
book_obj = models.Book.objects.first()
book_obj.authors.set([2, 3])
remove()
從關聯對象集中移除執行的model對象
book_obj = models.Book.objects.first()
book_obj.authors.remove(3)
clear()
從關聯對象集中移除一切對象。
book_obj = models.Book.objects.first()
book_obj.authors.clear()
注意:
對於ForeignKey對象,clear()和remove()方法僅在null=True時存在。
舉個例子:
ForeignKey字段沒設置null=True時,
class Book(models.Model): title = models.CharField(max_length=32) publisher = models.ForeignKey(to=Publisher)
沒有clear()和remove()方法:
>>> models.Publisher.objects.first().book_set.clear() Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'RelatedManager' object has no attribute 'clear'
當ForeignKey字段設置null=True時,
class Book(models.Model): name = models.CharField(max_length=32) publisher = models.ForeignKey(to=Class, null=True)
此時就有clear()和remove()方法:
>>> models.Publisher.objects.first().book_set.clear()
注意:
對於所有類型的關聯字段,add()、create()、remove()和clear(),set()都會馬上更新數據庫。換句話說,在關聯的任何一端,都不需要再調用save()方法。