【问题标题】:Django max_length of another model attribute另一个模型属性的 Django max_length
【发布时间】:2019-03-18 12:11:52
【问题描述】:

我想让一个模型属性的整数值成为另一个模型属性的 max_length,如下所述“容量 = 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)

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

【问题讨论】:

  • IntergerField 没有属性max_length
  • 我不明白你想要达到什么目的。你能补充一个更好的解释吗?
  • 如果您始终可以通过my_event.concerthallName.capacity 访问大厅容量,为什么需要这样做?为什么需要将容量存储两次?
  • 抱歉解释不好。音乐厅的容量是静态的,例如400人。但是某个事件的容量不是。可能是 350 或 200,但绝对不会超过 400。

标签: python django django-models maxlength


【解决方案1】:

我建议另一种方法,在模型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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多