django - 获取名称为动态的字段

rob*_*s85 8 python django

我需要的是:我想从DB获取对象详细信息.我使用get()函数.我遇到的问题是,我在函数中输入,其中一个参数是字段名称为字符串:

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)
Run Code Online (Sandbox Code Playgroud)

现在 - 我怎么做我能得到的东西old_image.field_name - 怎么做?

cwa*_*ole 21

你知道,我一开始认为这是你的答案 - 它让你通过动态属性进行搜索:**运营商可以工作吗?

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)
Run Code Online (Sandbox Code Playgroud)

但是,如果您已经拥有了所需的对象,并且只需要获取动态命名属性的值,那么您可以使用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)
Run Code Online (Sandbox Code Playgroud)