如何在Django中更新M2M字段 [英] How to .update m2m field in django

查看:104
本文介绍了如何在Django中更新M2M字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

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()

可以在具有更新的DB服务器上完成吗?

Can it be done on DB server with update?

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


好的,我无法更新,谢谢.但是我唯一需要做的就是截断m2m内部表,是否可以从Django执行?在mysql的控制台"SHOW TABLES"之外,如何知道它的名称?


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

推荐答案

查询1:

否,您不能使用 .update() 方法来更新 ManyToManyField .

Django的.update()方法不支持ManyToManyField.

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

根据

您只能设置非关系字段,并且 ForeignKey 字段使用此 方法..要更新非关系字段,请提供新值作为 持续的.要更新ForeignKey字段,请将新值设置为新值 您要指向的模型实例.

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.

查询2:

如果要删除m2m表的所有对象,可以使用

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

另一种方法是直接执行原始SQL.这种方法比以前的方法要快.

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

查询3:

要获取模型的表名,可以使用 db_table 模型Meta选项.

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

这篇关于如何在Django中更新M2M字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆