Search code examples
djangomany-to-many

What is the result of the add function in manytomany?


this is my model

class MyUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    items = models.ManyToManyField(Item, related_name='myuser')

when i write following code

MyUser.items.add(item1)

i want to know if it was added or duplicated


Solution

  • In short, the myuser.items will be a set, which means it won't create any duplicate entries even we are forcing to do so

    Example:

    In [1]: from django.contrib.auth.models import User
    
    In [2]: item = Item.objects.create(field_name="some_value")
    
    In [3]: usr = User.objects.get(id=1)
    
    In [4]: myuser = MyUser.objects.create(user=usr)
    
    In [5]: myuser.items.count()
    Out[5]: 0
    
    In [6]: myuser.items.add(item)
    
    In [7]: myuser.save()
    
    In [8]: myuser.items.count()
    Out[8]: 1
    
    In [9]: myuser.items.add(item)
    
    In [10]: myuser.save()
    
    In [11]: myuser.items.count()
    Out[11]: 1
    


    Here you can see, the count is not increasing while we adding the same item instance again and again