My model:
class Sample(models.Model):
users = models.ManyToManyField(User)
I want to save both user1 and user2 in that model:
user1 = User.objects.get(pk=1)
user2 = User.objects.get(pk=2)
sample_object = Sample(users=user1, users=user2)
sample_object.save()
I know that’s wrong, but I’m sure you get what I want to do. How would you do it ?
You cannot create m2m relations from unsaved objects. If you have the
pks, try this:Update: After reading the saverio’s answer, I decided to investigate the issue a bit more in depth. Here are my findings.
This was my original suggestion. It works, but isn’t optimal. (Note: I’m using
Bars and aFooinstead ofUsers and aSample, but you get the idea).It generates a whopping total of 7 queries:
I’m sure we can do better. You can pass multiple objects to the
add()method:As we can see, passing multiple objects saves one
SELECT:I wasn’t aware that you can also assign a list of objects:
Unfortunately, that creates one additional
SELECT:Let’s try to assign a list of
pks, as saverio suggested:As we don’t fetch the two
Bars, we save twoSELECTstatements, resulting in a total of 5:And the winner is:
Passing
pks toadd()gives us a total of 4 queries: