Hi,

I asked the same question earlier.
When ID is set to None and object is saved, the M2M fields are not 
copied. They must be copied separately.
Caveats: the code below uses django internals and is very lightly tested.

def copy_m2m_fields(src, dst):
    for m2m_field in src._meta.many_to_many:
        attname = m2m_field.get_attname()
        src_manager = getattr(src, attname)
        # idea from django/core/serializers/python.py,base.py
        # ... collect primary keys
        ids = [related._get_pk_val() for related in src_manager.iterator()]
        # ... assign id list to target field
        setattr(dst, attname, ids)
    dst.save()


Jacob Kaplan-Moss wrote:
> Hi Dave --
>
> I'm not sure what's going on in your code example, but there's a
> *much* easier way of copying an object::
>
>     >>> o = MyModel.objects.get(pk=1)
>     >>> o.id = None
>     >>> o.save()
>
> By setting the ID (or whatever your primary key is called) to ``None``
> and calling save() you'll force Django to insert a new object instead
> of updating the existing one. All that monkeying with ``__dict__``
> isn't really needed.
>
> /me makes note to think about adding an ``obj.copy()`` method...
>
> Jacob
>
> >
>
>   


--~--~---------~--~----~------------~-------~--~----~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to