2

I know this question has been posted multiple times but I still couldn't find a definite answer to this problem. So, here I go:

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)

Everything works fine except self.participants.count() doesn't work. Any idea what could be the problem. Any help much appreciated.

4

4 回答 4

5
self.participants.all().count()
于 2009-12-08T05:39:43.250 回答
0

我有一个类似的问题。我有一个支持 del.icio.us 样式标签的模型。保存函数将解析标签列表(例如“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']
于 2009-07-13T05:25:09.083 回答
0

我建议不要覆盖保存方法,而是使用预保存信号。除了让你的代码更简洁之外,它还有助于避免像这样的奇怪问题 :)

于 2009-06-06T20:55:53.473 回答
0

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

相反,其他参与者可能不会被保存到数据库中。无论哪种方式,无论使用信号如何,在保存期间取决于此数字都将不起作用。我建议使用单独的方法来执行此计算。它更干净,它提高了保存性能,您可以在不保存的情况下调用它。

于 2009-06-08T16:47:34.300 回答