Brian Fisher
Brian Fisher

Reputation: 23989

How to Set Multiple Fields in Django Db Record

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?

Upvotes: 3

Views: 5909

Answers (2)

Rahul Soni
Rahul Soni

Reputation: 36

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)

Upvotes: 0

Brandon Taylor
Brandon Taylor

Reputation: 34553

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)

Upvotes: 6

Related Questions