On Sep 29, 6:43 am, bruno desthuilliers
<bruno.desthuilli...@gmail.com> wrote:
> On 29 sep, 12:31, Steve Holden <holden...@gmail.com> wrote:
>
> > On 9/29/2010 5:25 AM, Daniel Roseman wrote:
> > > 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))
>
> Indeed. Note that you may not want to copy foo.pk (or at least not
> under the same name) if there's more than one Spam created for each
> Foo !-)
>
> <OP>
> If your system actually creates a new Spam instance each time the
> "certain action" is performed against Foo, you could as well create
> the whole attributes dict and pass it to Spam.objects.create, ie:
>
> attribs = dict((fielname, getattr(foo, fieldname))
> for fieldname in foo._meta.get_all_field_names()
> if fieldname is not 'id' # or whatever the pk name is
> )
>
> attribs.update(
> foo=foo,
> additional_attrib1='dead parrot',
> additional_attrib2='Norwegian Blue'
> )
>
> spam = Spam.objects.create(**attribs)
>
> HTH
--
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