【问题标题】:Django model DateField attribute limit choicesDjango 模型 DateField 属性限制选择
【发布时间】:2020-03-09 22:04:46
【问题描述】:

背景:所以我试图建立一个“账单”模型,其属性包括名称(收款人姓名)、金额(支付多少美元)和支付日期(何时支付账单) .

我遇到的问题:我很难将 PayDate 输入从 1(月初)限制为 31(本月最后一天(取决于月份) ))

这是我的模型代码:

from django.db import models

# Create your models here.


class Bill(models.Model) :
    Name = models.CharField(max_length=200, editable=True, blank=False)
    Amount = models.DecimalField(editable=True, blank=False, decimal_places=2, max_digits=6)
    PayDate = models.IntegerField(
        blank=False, editable=True)

def __str__(self):
    return f"{self.Name} @ ${self.Amount} every {self.PayDate} of the month"

我很想听听您关于如何设置 PayDate 属性的建议。

【问题讨论】:

  • 你有没有尝试过,做过任何研究?我很难相信没有关于如何做到这一点的信息。为什么将日期存储为整数,而不使用正确的日期/时间类型?

标签: python django django-models datefield


【解决方案1】:

IntegerFields 有一个MinValueValidator 和一个MaxValueValidator。验证器可以这样使用:

PayDate = models.IntegerField(
        blank=False, editable=True, validators=[MinValueValidator(1),MaxValueValidator(31)])

如果您希望根据月份更改最大值,则必须在表单中执行此操作,因为模型上的验证是固定的

【讨论】:

    【解决方案2】:

    您必须使用DateField 来存储付款日期。通过这样做,它将始终是一个有效的日期。通过添加auto_now_add=False,您还可以编辑该字段。

    from django.db import models
    
    # Create your models here.
    
    
    class Bill(models.Model) :
        Name = models.CharField(max_length=200, editable=True, blank=False)
        Amount = models.DecimalField(editable=True, blank=False, decimal_places=2, max_digits=6)
        PayDate = models.DateField(blank=False, auto_now_add=False)
    
    def __str__(self):
        return f"{self.Name} @ ${self.Amount} every {self.PayDate} of the month"
    

    【讨论】:

      猜你喜欢
      • 2012-06-13
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多