'How Do You Properly Copy ManyToMany Fields From One Model To Another
I am trying to override the SAVE of one model and copy specific fields to another model. I swear I had this working....but now it's not. Anyway...Here's an example of what I thought used to work....
def save(self, *args, **kwargs):
super(MyModel, self).save(*args, **kwargs)
NewModel = Target.objects.create( field=self.field )
NewModel.m2mfield.add(*self.m2mfield.all())
I swear this use to work but now when it gets executed...the "normal" fields copy as expected but the M2M is blank. I've confirmed that the model shows the values in the M2M field....but for whatever reason they aren't being copied over to the "Target" model.
Thanks in advance for any thoughts on what I might be doing wrong or what may have chnanged.
Solution 1:[1]
It looks good. Did you rename m2mfield? Should it be m2mfield_set?
Do you get the relatives when you print (self.m2mfield.all())?
Style opinion: use snake_case for instances (ie. NewModel -> new_model). Save the InitialCaps case for classes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dizzidude |
