Update_or_create with ManyToManyField

I have 2 models, for example:

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 the tag field - add new values. How to update a user instance using the update_or_create method?

For instance:

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

If the user "test_user" does not exist, it must be created, or if it exists, tag_1 must be added to this user.

+8
source share
2 answers

It is not possible to add tags to update_or_create because tags are ManyToManyField and therefore ManyToManyField staging table for database queries.

However, you can do this in two lines using get_or_create :

 user = Users.objects.get_or_create(name='test_user') user.tags.add(tag_1) 
+6
source

Data and all data will allow the creation and updating of data. Maybe someone will come in handy

 #     # first_name  second_name -   # defaults -           User.objects.update_or_create( first_name='Name', second_name='SecondNAme', defaults={'enter code here' 'first_name': 'You data', 'second_name': 'You data' } ) #    tag     tag =list(Subs.object.all()) # Subs.object.filter(tag=''some_tag) User.tag.set(tag_list) #     
0
source

All Articles