How to Set Multiple Fields in Django Db Record
I would like to know the best way to set the values for mul开发者_开发知识库tiple 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?
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)
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)
精彩评论