gpt4 book ai didi

python - Django max_length 另一个模型属性

转载 作者:行者123 更新时间:2023-12-01 01:07:16 24 4
gpt4 key购买 nike

我希望一个模型属性的整数值是另一个模型属性的 max_length,如下所述“capacity = models.IntegerField(ma​​x_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')

关于python - Django max_length 另一个模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55221097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com