Reputation: 567
I want to know if there is a function I can call in Django ORM to update the intermediate table by passing an array of IDs
Im used to work with Laravel, and that framework has a very useful method called sync. The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table is there something like that in Django? I was looking through the documentation but I can't find it. If there isn't, what's the best way to do it?
Upvotes: 1
Views: 1089
Reputation: 20672
You usually don't work with the ids in Django, but with the objects themselves. If you have a list of objects you want to set as the many-to-many relationship (making sure old relationships are removed), use set()
. E.g. publication.articles.set([article1, article2])
.
See this page for more examples on how to work with many-to-many relationships.
If you have a form that lets users select the objects to choose, using a ModelMultipleChoiceField
will return the list of objects in the form's cleaned_data
, rather than the ids.
Upvotes: 2