开发者

Trying to Nullify Django model fields with method where model and fields are parameters

I'm trying to write a method like the below where a list of fields (a subset of all the fields) is passed in as a parameter and has their column values set to null. I would be happy of I could get a method with just the fields as a parameter like below, but having the model as a parameter would be even better.

from my_project.my_app.models import MyModel

def nullify_columns (self, null_fields):
    field_names = MyMo开发者_如何学运维del._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) 

Right now I have something like

if 'column1' in list_of_fields:
    MyModel.objects.all().update(column1 = None) 
if 'column2' in list_of_fields:
    MyModel.objects.all().update(column2 = None)

etc. which is horrible, but works.


It's in the tutorial:

MyModel.objects.all().update(**dict.fromkeys(null_fields))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜