如何将字符串中的模型保存为字段名?

时间:2017-12-11 15:33:15

标签: python django django-models

我正在尝试将一些信息保存到我的模型中,因为我的fieldname列表是动态的,我想循环并将这些信息保存到字段而不是使用条件。

models.py

class Company(models.Model):
    name = ...
    email = ...
    phone = ...
    ...

views.py

company = get_object_or_404(Company, slug=slug)
text_fields = ['name', 'email', 'phone', 'organisation', 'address', 'website'] #dynamic list, might change depending the user's interaction.

for index, json_dt in enumerate(data): #data consists of JSON
    texts = json_dt['texts']

    for text in texts.values():
        for field in text_fields: # <-- loop through the list of fieldnames
            if text['key'] == field: # if json key is equal to fieldname
                company.field = text['fields']['text'] # save the JSON key's value to the field
                # Doesn't work because 'field' is a string, what's the solution ?

我怎样才能做到这一点?

0 个答案:

没有答案