3

I would like to know the best way to set the values for multiple fields of an existing Django model object. I have a model that includes many fields:

class Foo(models.Model):
    Field1 = models.CharField(max_length=40)
    Field2 = models.CharField(max_length=40)
    Field3 = models.CharField(max_length=40)
    etc...

Also I have dictionary containing changes to a subset of those fields for a particular record:

data = {'field1': 'value1', 'field5': 'value5', 'field7': 'value7'}
record = Foo.objects.get(pk=1)

I want to set the fields in record with the new values in data. What is the best way to go about this? Is there a way to unpack the dictionary and have it modify the appropriate fields in the record? I realize I can iterate over the dictionary using:

for k, v in data.iteritems():
     setattr(entry, k, v)
entry.save()

I was thinking there might be a way to call something like:

entry.set_values(**data)

Is there anything like this or am I going down the wrong path?

2 Answers 2

6

I haven't tested this myself, but you can probably pass a dict to the .update() function from the Queryset API: https://docs.djangoproject.com/en/2.0/ref/models/querysets/#update

Foo.objects.get(pk=1).update(**data)
Sign up to request clarification or add additional context in comments.

5 Comments

Update is only available on querysets but this works Foo.objects.filter(pk=1).update(**data). Thanks for the suggestion.
Do note that this will not fire any of the save-related signals, nor call .save() on the instance. This may be a desired situation, or a deal-breaker. You can do Foo.objects.filter(pk=1).update(**date); Foo.objects.get(pk=1).save() if you need this to fire.
the is link broken.
@Cyzanfar Fixed
0

Correction on @brandon answer.

Make sure to use .filter() method instead of .get() since .get method returns matching object or raise DoesNotExist exception

Wrong : Foo.objects.get(pk=1).update(**data)

Correct : Foo.objects.filter(pk=1).update(**data)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.