在save()中获取新创建的对象的ID [英] Getting ID of newly created object in save()

查看:1169
本文介绍了在save()中获取新创建的对象的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保存一个对象,使M2M得到保存。然后我想读出M2M领域做一些计算,并在保存的对象上设置一个字段。

  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)
#与M2M项目有一些关系

m2m_items不会出现。有没有办法得到这些?

解决方案

这里有些混乱。



一旦您调用 super self.id 将有一个值。



但是,我不明白您的过滤器调用的要点。首先,你可能意味着 get 而不是 filter ,因为过滤器获取了查询集,而不是单个实例。但是即使如此,这个通话是毫无意义的:你只需要保存它,所以从数据库返回的任何内容将是完全一样的。有什么要点?



问题更新后修改确定,感谢您的澄清。但是,该模型的 save()方法不对M2M项目做任何事情负责。他们需要单独保存,这是表单或视图的工作。


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 ?

解决方案

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.

这篇关于在save()中获取新创建的对象的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆