What I need: I want to get object details from DB. I use get() function. The problem I have is, that I make in in a function, and one of the arguments is field name as string:
def delete_file_if_changed(id, change, form, m开发者_如何学Codel, field_name='image'):
if change:
if field_name in form.changed_data:
old_image = model.objects.get(pk__exact=id)
Now - how can I do the thing that I can get old_image.field_name - how to do that?
You know, I thought this was your answer at first -- it lets you search by a dynamic property: Could the **
operator work?
kw = {field_name:change} # you're not explicit as to which is the field_name
# value you would like to search for.
old_image = model.objects.get(**kw)
But, if you already have the object you want, and you just need to get the value of a dynamically named property, then you can use getattr(object, name[, default])
:
getattr(old_image, "id", "Spam") # gets old_image.id, if that does not exist, it
# defaults to the str "Spam" Of course, in this
# context, you probably want
# getattr(old_image, field_name)
What about getattr(old_image, field_name)
? More info in documentation.
If you only want the field value, avoid the whole process of building out the model instance and getting the value, just query it directly from the database:
field_value = model.objects.values_list(field_name, flat=True).get(pk__exact=id)
精彩评论