如何在Django中更新M2M字段 [英] How to .update m2m field in django
问题描述
我有:
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.
根据
您只能设置非关系字段,并且 You can only set non-relation fields and 查询2: If you want to delete all the objects of m2m table, you can use 另一种方法是直接执行原始SQL.这种方法比以前的方法要快. Another method is to execute the raw SQL directly. This method is faster than the previous one. 查询3: 要获取模型的表名,可以使用 To get the table name of a model, you can use 这篇关于如何在Django中更新M2M字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!ForeignKey
字段使用此
方法..要更新非关系字段,请提供新值作为
持续的.要更新ForeignKey
字段,请将新值设置为新值
您要指向的模型实例.
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..delete()
queryset method.MyModel.objects.all().delete() # deletes all the objects
from django.db import connection
cursor = connection.cursor()
cursor.execute("TRUNCATE TABLE table_name")
db_table
模型Meta
选项.db_table
model Meta
option.my_model_object._meta.db_table # gives the db table name