Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an object by id in a ManyToMany relation in Django

Django's ManyToMany field can be populated using my_field.add(my_instance), but as I understand it only my_instance.id is actually needed to perform the corresponding SQL query.

If I want to add an object by its id, I can use my_field.add(MyModel.objects.get(id=id)), but this will generate two queries instead of one. How can I avoid this extra query?

like image 961
pintoch Avatar asked May 29 '16 15:05

pintoch


1 Answers

Although the documentation of the add method does not mention it, you can actually pass directly an id to it, like this:

my_instance.add(id)

Surely, this only works when the primary key is used as the identifier for the relation (the default behaviour).

like image 123
pintoch Avatar answered Sep 18 '22 15:09

pintoch