我有这些模特:
#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)
....
....
在admin上创建一个新的Invoice实例时,我可以选择多个到多个字段的“活动”,但是我希望有一个额外的计数器(例如,一个IntegerField)作为Invoice字段来计算和保存数量每个活动添加到我的Invoice实例中。这可能吗?
感谢,
路
答案 0 :(得分: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()