Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 849
Mike Avatar asked Aug 25 '15 11:08

Mike


1 Answers

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 = Users.objects.get_or_create(name='test_user')
user.tags.add(tag_1)
like image 159
Leistungsabfall Avatar answered Sep 18 '22 16:09

Leistungsabfall