When you pass a list of pk integers into add or remove – are the objects accessed? ie. Is there a database call for each pk?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
When you create a
ManyToManyFieldwithout specifying an intermediary table (usingthrough) Django generates a table for you. This table will only need the pks of both models, so there’s no need to select anything from the other objects in order to save the new relashionships.A new row will be created for each of them, possibly using many inserts, but not necessarily many database calls (a single SQL query with multiple insert commands, for instance, is possible). All the info needed for those creations (the pks of your objects) are readily available, so no need for any more database hits than necessary.
Update: seems I was mistaken. Looking at the sources (django/db/models/fields/related.py), I saw that it performs an independent creation for each object:
Before doing that, it also checks if any of the pks supplied already existed in the database (in order to avoid duplicate entries/uniqueness constraint violations):
This check is done with a single query though…