Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to .update m2m field in django

I have:

class MyUser(Model):
    today_ref_viewed_ips = ManyToManyField(
        UniqAddress, 
        related_name='today_viewed_users', 
        verbose_name="Adresses visited referal link today")
    ...

On some croned daily request I do:

for u in MyUser.objects.all():
    u.today_ref_viewed_ips.clear()

Can it be done on DB server with update?

MyUser.objects.all().update(...)

Ok, I can't update, thanks. But only thing I need is to TRUNCATE m2m internal table, is it possible to perform from django? How to know it's name whithout mysql's console "SHOW TABLES"?

like image 437
Ivan Borshchov Avatar asked Sep 13 '15 18:09

Ivan Borshchov


People also ask

How do I update a specific field in Django?

Use update_fields in save() If you would like to explicitly mention only those columns that you want to be updated, you can do so using the update_fields parameter while calling the save() method. You can also choose to update multiple columns by passing more field names in the update_fields list.

How do I update ManyToMany fields?

You need to use . set() or . add() for updating a M2M field.

How do I update many-to-many relationships in Django?

Updating A Post With Tags This is the primary purpose of this article—updating the many to many relationship between the post and tags. To update the post along with the tags, we need to add another view function called update_post .


1 Answers

If you want to update the m2m fields only and do not want to delete the m2m objects you can use the following:

#if you have **list of pk** for new m2m objects

today_ref_pk = [1,2,3]
u = MyUser.objects.get(pk=1)
u.today_ref_viewed_ips.clear()
u.today_ref_viewed_ips.add(*today_ref_pk)

for django >=1.11 documentation:

# if you have the **list of objects** for new m2m and you dont have the 
# issue of race condition, you can do the following:

today_ref_objs = [obj1, obj2, obj3]
u = MyUser.objects.get(pk=1)
u.today_ref_viewed_ips.set(today_ref_objs, clear=True)
like image 73
sgauri Avatar answered Oct 20 '22 05:10

sgauri