Wednesday, September 29, 2010

Re: What is the correct way to copy an object from one model to a similar model?

On 9/29/2010 5:25 AM, Daniel Roseman wrote:
> On Sep 29, 6:06 am, Yo-Yo Ma <baxterstock...@gmail.com> wrote:
>> I have two models that are identical in structure except one has 2
>> extra fields. The second one is used for record keeping and is never
>> edited by users. The system takes the first model and copies it to the
>> second model, adding some extra meta information, all when a certain
>> action is performed against the first model.
>>
>> What is the best practice for this?
>>
>> spam.attribute_one = foo.attribute_one
>> spam.attribute_two = foo.attribute_two
>>
>> Or, is there a pattern that works well?
>
> You can use the get_all_field_names method in model._meta to get all
> the actual fields, and set them on the duplicate:
>
> for field in foo._meta.get_all_field_names():
> setattr(spam, getattr(foo, field))
>
I believe that last line should read

setattr(spam, field, getattr(foo, field))

regards
Steve
--
DjangoCon US 2010 September 7-9 http://djangocon.us/

--
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