在保存到数据库之前在会话中使用实例
我有一个有几个步骤的系统。每一步都会增加一个对象实例。 我只想在最后一步将实例保存在数据库中,而其他步骤只需更新我在会话中保存的实例。
我的模型类看起来像这样:
class Proposta(models.Model):
Modelo = models.ForeignKey("ModeloVersao", verbose_name="Modelo")
Pacotes = models.ManyToManyField("PacoteModelo", null=True, blank=True)
Opcionais = models.ManyToManyField("ItemModelo", null=True, blank=True)
RevestimentoInterno = models.ForeignKey("RevestimentoInternoModelo", verbose_name="Revestimento Interno")
Cor = models.ForeignKey("CorModelo")
CorSecundaria = models.ForeignKey("CorModeloSecundaria", verbose_name="Cor secundária", null=True, blank=True)
Data = models.DateTimeField(auto_now_add = True)
Status = models.CharField("Status", choices=STATUS_PROPOSTA, max_length=10)
Cliente = models.ForeignKey("Cliente")
这是我的问题: 当我尝试添加或检索 m2m 字段时,它显然会抛出 ValueError 并显示消息 'Proposta' 实例需要有主键值才能使用多对多关系。
我成功获得了通过创建 pk=0 的 obj 实例来获得想要的结果,但我确信这不是最好的方法(如果有的话)。
确实存在一种无需像这样作弊的方法。
任何帮助都会很棒。
谢谢
I have a system with several steps. Each step increments one single object instance.
I want to save the instance in db only in the final step, on others just update the instance I saved in the session.
My model class seems like this:
class Proposta(models.Model):
Modelo = models.ForeignKey("ModeloVersao", verbose_name="Modelo")
Pacotes = models.ManyToManyField("PacoteModelo", null=True, blank=True)
Opcionais = models.ManyToManyField("ItemModelo", null=True, blank=True)
RevestimentoInterno = models.ForeignKey("RevestimentoInternoModelo", verbose_name="Revestimento Interno")
Cor = models.ForeignKey("CorModelo")
CorSecundaria = models.ForeignKey("CorModeloSecundaria", verbose_name="Cor secundária", null=True, blank=True)
Data = models.DateTimeField(auto_now_add = True)
Status = models.CharField("Status", choices=STATUS_PROPOSTA, max_length=10)
Cliente = models.ForeignKey("Cliente")
Here's my problem:
When I try to add or retrieve m2m fields it obviously throws a ValueError with the message 'Proposta' instance needs to have a primary key value before a many-to-many relationship can be used.
I successfully got the wanted result by creating my obj instance with pk=0 but I'm sure it isn't the best way, if there is.
Do exist a way of doing that without cheating like this.
Any help would be great.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能会找到这个问题的答案 有帮助。
快速参考摘要:
我可能会补充说文档专门解释了如何处理M2M 字段,在解释
save()
方法。其中,我建议使用 ModelForms。希望这有帮助!
You might find the answers to this question helpful.
Summary for quick reference:
I might add that the documentation specifically explains how to deal with M2M fields, in the section that explains The
save()
method.Of those, I recommend using ModelForms. Hopefully this helps!