我正在尝试将一些信息保存到我的模型中,因为我的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 ?
我怎样才能做到这一点?