將許多實例添加到相關字段的主要問題是它會導致性能問題。 這是因為數據庫必須跟踪所有實例,這會導致性能下降。
%5B%5D=1&django%5D%5B%5D=2&django%5D%5B%5D=3 I have a model with a many to many relationship: <code>class MyModel(models.Model): related_field = models.ManyToManyField(RelatedModel) </code> In the admin interface, I can add multiple instances of <code>RelatedModel</code> to <code>related_field</code>. How can I do this in code? The following doesn't work: <code>mymodel = MyModel() mymodel.related_field = [1, 2, 3] # doesn't work! only adds 1 instance of RelatedModel to related_field. mymodel.save() # only saves one instance of RelatedModel in related_field! </code> A: mymodel = MyModel() mymodel.save() mymodel.related_field = [1, 2, 3] mymodel.save()
多對多關係
多對多關係是兩個實體之間的一種關係,其中每個實體都可以與另一個實體建立多個關係。 例如,一個人可以有很多朋友,一個朋友可以有很多朋友。 在 Django 中,多對多關係由具有兩個字段的模型實例表示:一個用於第一個實體,一個用於第二個實體。
如何將多個對象添加到多對多關係
要在 Django 中將多個對象添加到 ManyToMany 關係中,您可以在 many_to_many 對像上使用 add() 方法。 例如,要在 Django 中將博客文章和作者添加到博客文章的多對多關係中,您將使用以下代碼:
blog.add(BlogPost.objects.create(title='Adding Multiple Objects to a ManyToMany Relationship', content=content)) author = Author.objects.create(name='John Doe')
您還可以在 many_to_many 對像上使用 join() 方法將對象組合成一個結果集:
blog.join(作者)