Search code examples
sqldjangomany-to-many

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"?


Solution

  • Query-1:

    No, you cannot use .update() method to update a ManyToManyField.

    Django's .update() method does not support ManyToManyField.

    As per the docs from the section on updating multiple objects at once:

    You can only set non-relation fields and ForeignKey fields using this method. To update a non-relation field, provide the new value as a constant. To update ForeignKey fields, set the new value to be the new model instance you want to point to.

    Query-2:

    If you want to delete all the objects of m2m table, you can use .delete() queryset method.

    MyModel.objects.all().delete() # deletes all the objects
    

    Another method is to execute the raw SQL directly. This method is faster than the previous one.

    from django.db import connection
    cursor = connection.cursor()
    cursor.execute("TRUNCATE TABLE table_name")
    

    Query-3:

    To get the table name of a model, you can use db_table model Meta option.

    my_model_object._meta.db_table # gives the db table name