Blake Russell
Blake Russell

Reputation: 61

Update QuerySet by attribute variable

Take for example my data below where prop is the queryset I am trying to update, and results is a dict of information. This dict has keys that are attributes in this queryset, and also has keys that are not attributes in this QuerySet . I only want to update this QuerySet if it's attribute matches...

prop = Property.objects.get(pk=14)
results = {'price': '525000', 'code': '55285', 'estimate': '1500'}

I know this does not work as it calls for an attribute literally named 'apicall' but this is the logic that I am looking to achieve:

for apicall in results:
 if hasattr(prop,apicall):
  prop.apicall = results[apicall]
  prop.save()

How can I avoid calling literally prop.apicall and instead prop.price if it exists in the queryset?

Upvotes: 1

Views: 95

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You can work with the setattr(…) builtin function [python-doc], and thus use:

for apicall in results:
    if hasattr(prop,apicall):
        setattr(prop, apicall, results[apicall])
prop.save()

It is likely better to save prop after all the changes, otherwise we will perform a lot of extra database queries.

Upvotes: 1

Related Questions