【发布时间】:2011-02-09 18:06:13
【问题描述】:
我正在尝试编写如下方法,其中将字段列表(所有字段的子集)作为参数传入,并将其列值设置为 null。我很高兴我可以得到一个只使用字段作为参数的方法,如下所示,但是将模型作为参数会更好。
从 my_project.my_app.models 导入 MyModel
def nullify_columns (self, null_fields):
field_names = MyModel._meta.get_all_field_names()
for field in field_names:
if field in null_fields:
# The below line does not work because I'm not sure how to
# dynamically assign the field name.
MyModel.objects.all().update( (MyModel.get_field(field).column) = None)
现在我有类似的东西
if 'column1' in list_of_fields:
MyModel.objects.all().update(column1 = None)
if 'column2' in list_of_fields:
MyModel.objects.all().update(column2 = None)
等等。这是可怕的,但有效。
【问题讨论】: