Wednesday, June 30, 2010

Re: Proper approach to updating model object with 100 attributes.

I think you need to be careful messing with __dict__ as Django turns
most fields in descriptors behind the scenes so setting them in the
__dict__ could break these.

I'd stick to setattr and maybe verify that the key in the dictionary
is one of the model's fields. I think there is a method on _meta
called get_all_field_names. I've used this before to validate such
actions.

Euan

On 29 June, 19:03, Tim Chase <django.us...@tim.thechases.com> wrote:
> On 06/29/2010 12:01 PM, Ray Cote wrote:
>
>
>
>
>
> > Hi List:
>
> > I have a Django model with over 100 fields in it that is loaded from a data feed.
> > Each row in the model has a unique field, let's call it item_id.
> > When loading new data, I'm first checking to see if item_id is in the table,
> > if it is, I want to update it with the new data from the new 100 fields.
>
> > To date, I've done things like:
>
> > obj = Model.objects.get(item_id = item_id_from_field)
>
> > and then.
> > obj.field1 = new_field1
> > etc.
>
> > However, for 100 fields, I'd like to find something a bit cleaner than listing 100 fieldnames.
> > The data for the new 100 fields is in a nice dictionary.
>
> > When I create a new item, I'm able to do this:
> >    obj = MyModel(**dictionary_of_field_values)
>
> > Is there something similar I can do with my obj once the data is retrieved?
>
> Well, you could do something like
>
>    for name, value in dictionary_of_field_values.items():
>      setattr(obj, name, value)
>
> or possibly even just
>
>    obj.__dict__.update(dictionary_of_field_values)
>
> (I'm not sure how this interacts with Django's meta-class
> yumminess, but it works for regular Python classes)
>
> -tkc

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment