另一个模型属性的Django max_length

时间:2019-03-18 12:11:52

标签: python django django-models maxlength

我希望一个模型属性的整数值为另一个模型属性的max_length,如下所述:“ capacity = models.IntegerField( max_length = Concerthall.capacity )”。

class Concerthall(models.Model):
    name = models.TextField(max_length=254)
    capacity = models.IntegerField()
    employees = models.IntegerField()

    def __str__(self):
    return self.name

class Events(models.Model):
    name = models.TextField(max_length=254)
    capacity = models.IntegerField(max_length=Concethall.capacity)
    timeFrom = models.DateTimeField()
    timeTo = models.DateTimeField()
    concerthallName = models.ForeignKey(Concerthall, on_delete=models.PROTECT, null=True)

也许它也与验证器一起工作,但是我搜索了几个小时,却找不到任何解决方案。

1 个答案:

答案 0 :(得分:2)

我建议使用另一种方法,在模型clean()方法中进行验证:

class Events(models.Model):
    name = models.TextField(max_length=254)
    capacity = models.IntegerField(default=0)
    timeFrom = models.DateTimeField()
    timeTo = models.DateTimeField()
    concert_hall = models.ForeignKey(Concerthall, on_delete=models.PROTECT)

    def clean(self):
        if self.capacity > self.concert_hall.capacity:
            raise ValidationError(
                'the capacity of the event cannot exceed the capacity of the hall')