Django模型自定义保存带有多个字段问题

Django模型自定义保存带有多个字段问题,django,model,save,manytomanyfield,Django,Model,Save,Manytomanyfield,我知道这个问题已经被贴了很多次了,但是我仍然找不到这个问题的确切答案。所以,我要说: class Invoice(models.Model): program = models.ForeignKey(Program) customer = models.ForeignKey(Customer, related_name='invoices') participants = models.ManyToManyField(Participant, related_name='

我知道这个问题已经被贴了很多次了,但是我仍然找不到这个问题的确切答案。所以,我要说:

class Invoice(models.Model):
    program = models.ForeignKey(Program)
    customer = models.ForeignKey(Customer, related_name='invoices')
    participants = models.ManyToManyField(Participant, related_name='participants_set')
    subtotal = models.DecimalField(max_digits=10, decimal_places=2, default='0.00', blank=True, null=False)
    pst = models.DecimalField("PST", max_digits=10, decimal_places=2, default='0.00', blank=True, null=False)
    gst = models.DecimalField("GST", max_digits=10, decimal_places=2, default='0.00', blank=True, null=False)
    total = models.DecimalField(max_digits=10, decimal_places=2, default='0.00', blank=True, null=False)

    def save(self, **kwargs):
        super(Invoice, self).save(**kwargs)
        items = self.participants.count()
        subtotal = Decimal(self.program.fee) * items
        pst = self.program.is_pst and Decimal(PST)*subtotal or Decimal('0.00')
        gst = self.program.is_gst and Decimal(GST)*subtotal or Decimal('0.00')
        total = (subtotal + pst) + gst
        self.subtotal = subtotal
        self.pst = pst
        self.gst = gst
        self.total = total
        super(Invoice, self).save(**kwargs)

除了self.participants.count()不起作用外,其他一切都正常。你知道有什么问题吗。非常感谢您的帮助。

我建议使用。除了使您的代码更简洁之外,它还可以帮助您避免以下奇怪的问题:)

我认为发生的情况是因为您在保存过程中尝试参与者计数,查询可能无法找到所有内容。如果您在数据库创建时依赖于这个数字,我认为多对多表不会正确同步,因为
发票
尚未分配ID


相反,其他参与者可能不会保存到数据库中。无论采用哪种方式,在保存过程中依赖于此数字都无法工作,无论使用何种信号。我建议使用一种单独的方法来进行此计算。它更干净,提高了保存性能,您可以在不保存的情况下调用它。

我也遇到过类似的问题。我有一个支持del.icio.us样式标记的模型。save函数将解析标记列表(例如“python-django-web”),并通过调用助手函数update_-tags()(参见下面的简化示例)将它们转换为单个标记对象实例。但是,当我在管理界面中编辑对象时,ManyToManyField不会反映这些更改

class Article(models.Model):
    tag_string = models.CharField(max_length=255, null=True, blank=True) #del.icio.us style tags, like: django python software
    tags =  models.ManyToManyField(Tag, blank=True)

    def save(self, force_insert=False, force_update=False):
        super(Article, self).save(force_insert, force_update)

        self.update_tags() #The result of this function didn't seem to be saved in the ManyToManyField
结果是,管理接口覆盖了对ManyToManyField的更改。解决方案只是从admin.ModelAdmin中删除ManyToManyField:

class ArticleAdmin(admin.ModelAdmin):
    exclude = ['tags']

什么版本的Django?您对self.participants.count()的调用应该可以工作。count方法是否引发异常,或者它是否给出了错误的值?将参与者完全分开并只记录数量(参与者数量)听起来是个好主意。这样,发票模型将更加通用。
self.participants.all().count()