I think it's a good idea to provide a helper method in the Model class to
mass update the fields, particularly if it's a field with many fields.
--
Ticket URL: <https://code.djangoproject.com/ticket/25086>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* needs_better_patch: => 0
* needs_tests: => 0
* needs_docs: => 0
Old description:
> Sometimes we have an unpersisted model instance generated from, say, a
> factory. Before saving this to the database, we might want to do some
> additional processing to update the fields.
>
> I think it's a good idea to provide a helper method in the Model class to
> mass update the fields, particularly if it's a field with many fields.
New description:
Sometimes we have an unpersisted model instance generated from, say, a
factory. Before saving this to the database, we might want to do some
additional processing to update the fields.
I think it's a good idea to provide a helper method in the Model class to
mass update the fields, particularly if it's a model with many fields.
--
--
Ticket URL: <https://code.djangoproject.com/ticket/25086#comment:1>
* component: Uncategorized => Database layer (models, ORM)
Comment:
Could you give an example of the API you have in mind?
--
Ticket URL: <https://code.djangoproject.com/ticket/25086#comment:2>
Comment (by yoongkang):
Yep. I have a pull request on GitHub, but basically the method should take
a dictionary where the keys are the names of the field, and the values are
the updated field values.
This code snippet should do the trick:
{{{
def assign_attributes(self, values_dict):
keys = values_dict.keys()
fields = [f.name for f in self._meta.get_fields()]
for k in keys:
if k in fields:
setattr(self, k, values_dict[k])
}}}
There is a similar method in Rails which I'm used to using:
http://api.rubyonrails.org/classes/ActiveRecord/AttributeAssignment.html
--
Ticket URL: <https://code.djangoproject.com/ticket/25086#comment:3>
Comment (by timgraham):
I don't like the idea of silently ignoring values from `values_dict` if
they don't existing in fields. It seems this would make typos more
difficult to debug.
Overall, I don't have a strong opinion on whether or not this should be
part of Django, so I'd suggest to write to the DevelopersMailingList to
get some opinions. However, if we get rid of the fields logic, it seems
this boils down to two lines:
{{{
for k, v in values_dict.items():
setattr(instance, k, v)
}}}
so the value of adding a method for that doesn't seem significant. Of
course, you can create a model mixin if you really want it in your own
project.
--
Ticket URL: <https://code.djangoproject.com/ticket/25086#comment:4>
* status: new => closed
* resolution: => wontfix
--
Ticket URL: <https://code.djangoproject.com/ticket/25086#comment:5>