0

我有这些模型:

#model.py

class Subject(models.Model):
    name = models.CharField("Name",max_length=50, blank=True)
    ...
    ...

class Activity(models.Model):
    label = models.CharField("Act. name",max_length=150)
    price = models.DecimalField("price", max_digits=10, decimal_places=2,default=0)
    count = models.IntegerField("Count", default=0)

    def __unicode__(self):
        return u"%s" % (self.label)
    class Meta:
        verbose_name_plural = "Activities"


class Invoice(models.Model):
    subject = models.ForeignKey(Subject)
    date = models.DateField(default=date.today())
    activities = models.ManyToManyField(Activity)
    ....
    ....

在管理员上创建新的发票实例时,我可以选择多对多字段“活动”,但我希望有一个额外的计数器(例如 IntegerField)作为发票字段来计算和保存每个活动的数量添加到我的 Invoice 实例中。这可能吗?

谢谢,

卢克

4

1 回答 1

1

您可以在模型上有一个字段并覆盖保存方法

class Invoice(models.Model):
    subject = models.ForeignKey(Subject)
    date = models.DateField(default=date.today())
    activities = models.ManyToManyField(Activity)
    activity_count = models.PositiveIntegerField(default=0)
    def save(self):
       self.activity_count = self.activities.count()
       super(Invoice, self).save()
于 2012-11-12T23:34:55.587 回答