Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - get field which name is dynamic

Tags:

python

django

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, 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 the thing that I can get old_image.field_name - how to do that?

like image 594
robos85 Avatar asked Aug 08 '11 10:08

robos85


3 Answers

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)
like image 148
cwallenpoole Avatar answered Oct 21 '22 07:10

cwallenpoole


What about getattr(old_image, field_name)? More info in documentation.

like image 20
Marcin Świerczyński Avatar answered Oct 21 '22 08:10

Marcin Świerczyński


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)
like image 21
rewritten Avatar answered Oct 21 '22 06:10

rewritten