0

希望基于另一个字段创建默认值,类似于:

class Track(models.Model):
    distance = models.FloatField()
    timeout = models.PositiveSmallIntegerField(default=int(distance * 2))

然而这抛出TypeError: unsupported operand type(s) for *: 'FloatField' and 'int'

FWIW,我试过这个无济于事:

class Track(models.Model):
    distance = models.FloatField()
    timeout = models.PositiveSmallIntegerField()

    def save(self, *args, **kwargs):
        if (self.timeout is None):
            self.timeout = int(self.distance * 2)
            super(Track, self).save(*args, **kwargs)

但那是扔TypeError: 'int' object is not iterable

4

1 回答 1

0

Opps,应该更仔细地阅读堆栈跟踪,结果发现问题是我的单元测试中的一个错误,而不是实际代码:

def test_timeout_defaults_to_twice_distance_when_none(self):
    Track.objects.create(name='Test Track', distance=10)
    track = Track.objects.get(1) # Should've been get(id=1)
    self.assertEqual(20, track.timeout)

我不会删除这个问题,以防另一个 Python 和 Django noob 做同样的事情:)

于 2013-07-24T10:55:48.980 回答