Stephan
Stephan

Reputation: 87

Getting ID of newly created object in save()

I want to save an object, so that the M2M get saved. Then I want to read out the M2M fields to do some calculations and set a field on the saved object.

class Item(models.Model):
    name = models.CharField(max_length=20, unique=True)
    product = models.ManyToManyField(SomeOtherModel, through='SomeTable')

    def save(self, *args, **kwargs):
        super(Item, self).save(*args, **kwargs)
        m2m_items = SomeTable.objects.filter(item = self)
        # DO SOME STUFF WITH THE M2M ITEMS

The m2m_items won't turn up,. Is there any way to get these up ?

Upvotes: 3

Views: 2033

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

Some confusion here.

Once you've called super, self.id will have a value.

However, I don't understand the point of your filter call. For a start, you probably mean get rather than filter anyway, as filter gets a queryset, rather than a single instance. But even so, the call is pointless: you've just saved it, so whatever you get back from the database will be exactly the same. What's the point?

Edit after question update OK, thanks for the clarification. However, the model's save() method is not responsible for doing anything with M2M items. They need to be saved separately, which is the job of the form or the view.

Upvotes: 4

Related Questions