Trying to Nullify Django model fields with method where model and fields are parameters
Posted
by Johnny4000
on Stack Overflow
See other posts from Stack Overflow
or by Johnny4000
Published on 2010-04-19T15:33:59Z
Indexed on
2010/04/19
15:43 UTC
Read the original article
Hit count: 395
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 = 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)
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.
© Stack Overflow or respective owner