另一个模型属性的Django max_length

Django max_length of another model attribute

我想让一个模型属性的整数值成为另一个模型属性的 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)

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

我建议采用不同的方法,在模型 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')