On 6/29/10 4:20 PM, Ray Cote wrote:
Hi Tim:

Thanks for the pointers.
I think the setattr is probably safest way to deal with the Django models.

--Ray

----- Original Message -----
From: "Tim Chase"<django.us...@tim.thechases.com>
To: django-users@googlegroups.com
Cc: "Ray Cote"<rgac...@appropriatesolutions.com>
Sent: Tuesday, June 29, 2010 2:03:05 PM GMT -05:00 US/Canada Eastern
Subject: Re: Proper approach to updating model object with 100 attributes.

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




Perhaps you could use django.forms.models.model_to_dict() method? that is if you have existing object already and you need to retrieve it's attributes into a nice dict. PS. If I misunderstood your question, disregard everything i wrote and do accept my apologies :)


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

Reply via email to