[Fixed]-Copying ManyToMany fields from one model instance to another

15👍

The simpliest method I could come up with:

e = Expense(description=self.description,
            amount=self.amount,
            category=self.category,
            date=expense_date)
e.save()
e.tags = self.tags.all()
👤mac

21👍

You cannot set an m2m field directly like that when creating a model instance. Try the following instead:

expense = Expense(description=self.description,
        amount=self.amount,
        category=self.category,
        date=expense_date)
expense.save()
expense.tags.add(*self.tags.all())

You can check https://docs.djangoproject.com/en/1.4/topics/db/examples/many_to_many/ for more examples on how to work with many-to-many relationships.

Leave a comment