Opened 9 years ago

Closed 9 years ago

#25086 closed New feature (wontfix)

Allow mass-update of fields in unpersisted model instances

Reported by: Yoong Kang Lim Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Yoong Kang Lim)

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.

Change History (5)

comment:1 by Yoong Kang Lim, 9 years ago

Description: modified (diff)

comment:2 by Tim Graham, 9 years ago

Component: UncategorizedDatabase layer (models, ORM)

Could you give an example of the API you have in mind?

comment:3 by Yoong Kang Lim, 9 years ago

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

comment:4 by Tim Graham, 9 years ago

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.

comment:5 by Tim Graham, 9 years ago

Resolution: wontfix
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top