3

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 ?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Stephan
  • 87
  • 6

1 Answers1

4

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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Sorry my bad, I put the info wrong. I rewrote my question. What I do is I try to get the many2many items. But for some reason they won't turn up – Stephan Apr 14 '11 at 20:01
  • Thanks for you answer. Im trying to use the m2m_changed signal now. models.signals.m2m_changed.connect(set_total_price, sender=Deal.product.through) It won't call my set_total_price method for some reason. It works with the post_save signal... Ah well, I got some things to try again. Thanks alot. – Stephan Apr 14 '11 at 21:47
  • For further reading: I ended up reading the M2M in the save_formset by iterating over the instances. Then I called up the saved Item and saved that with the new value. – Stephan Apr 15 '11 at 12:14