希望根据另一个字段创建默认值,类似于:
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
答案 0 :(得分: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做同样的事情,我不会删除这个问题:)