Getting ID of newly created object in save()

烈酒焚心 提交于 2019-12-13 14:32:35

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/5668802/getting-id-of-newly-created-object-in-save

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!