Search code examples
djangodjango-modelsdjango-orm

update_or_create with ManyToManyField


I have 2 models, like this:

class Subs(models.Model):
    tag = models.CharField(max_length=100)

class Users(models.Model):
    name = models.CharField(max_length=100)
    tags = models.ManyToManyField(Subs)

I need to update tags field - add new values. How can I update instance of Users with update_or_create method?

For example:

tag_1 = Subs.object.get(pk=1)
Users.objects.update_or_create(name='test_user', tags=tag_1)

If user 'test_user' doesn't exist, it must be created, or if it exists tag_1 must be added to this user.


Solution

  • It's not possible to add tags in update_or_create because tags is a ManyToManyField and therefore involves an intermediate table for database queries.

    You can however do it in two lines using get_or_create:

    user, created = Users.objects.get_or_create(name='test_user')
    user.tags.add(tag_1)