Django - get a field whose name is dynamic

What I need: I want to get the details of the object from the database. I am using the get () function. The problem I have is that I enter the function, and one of the arguments is the field name as a string:

def delete_file_if_changed(id, change, form, model, 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 what old_image.field_name can get - how to do it?

+6
source share
3 answers

You know, I thought that was your answer at first - it allows you to search by dynamic property: can 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 desired object, and you just need to get the value of the property with a dynamic name, 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) 
+17
source

If you only need the field value, avoid the whole process of building an instance of the model and getting the value, just request it directly from the database:

 field_value = model.objects.values_list(field_name, flat=True).get(pk__exact=id) 
+1
source

What about getattr(old_image, field_name) ? Additional information in the documentation .

0
source

Source: https://habr.com/ru/post/894534/


All Articles