0

在我的 django 管理表单中,我有许多字段,用户可以在其中输入浮点数。我想对这些数字进行平均,并在提交表单时将平均值保存到相关外来对象的模型字段中。做这个的最好方式是什么?

编辑: 根据下面 fest 的回答,我尝试了:

class ForeignObject(models.Model):
  avg = models.FloatField()

class MyModel(models.Model):
  foreign_object = models.ForeignKey(ForeignObject)
  field1 = models.FloatField()
  field2 = models.FloatField()
  avg = models.FloatField(blank=True, null=True)

  def save(*args, **kwargs):
    self.foreign_object.avg = float(sum([self.field1, self.field2])) / 2 
    return super(models.Model, self.foreign_object).save(*args, **kwargs)

但收到异常:'super' object has no attribute 'save'尝试提交管理表单时。

4

2 回答 2

2

在模型的 save() 方法中设置平均值:

class MyModel(models.Model):
  field1 = models.FloatField()
  field2 = models.FloatField()
  avg = models.FloatField(blank=True, null=True)

  def save(self, *args, **kwargs):
    self.avg = float(sum([self.field1, self.field2])) / 2
    return super(models.Model, self).save(*args, **kwargs) 

您很可能还希望将avg字段设置为只读 - https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields

于 2012-05-26T19:36:11.883 回答
1

我认为你的代码应该是:

class ForeignObject(models.Model):
  avg = models.FloatField()

class MyModel(models.Model):
  foreign_object = models.ForeignKey(ForeignObject)
  field1 = models.FloatField()
  field2 = models.FloatField()
  avg = models.FloatField(blank=True, null=True)

  def save(self, *args, **kwargs):
    self.foreign_object.avg = float(sum([self.field1, self.field2])) / 2 
    self.foreign_object.save()
    super(MyModel, self).save(*args, **kwargs)

这假设 self.foreign_object 已经创建。此外, save 不返回任何值,因此不需要返回。

于 2012-05-26T23:33:06.857 回答