简体   繁体   English

在Django中创建数据库模型时,如何创建分别只接受一个月和一年的字段?

[英]When creating a database model in Django, how can I create fields that will only accept a month and year, respectively?

If I use something like 如果我使用类似

   year_published = models.DateField()

then I have to enter in a day and month, in addition to a year. 然后除了一年之外,我还必须输入一天和一个月。 But in this field I only want to enter a year. 但是在这个领域我只想输入一年。 Likewise, I only want to enter a month in 同样,我只想输入一个月

   month_published = models.DateField()

Any idea how to do this? 任何想法如何做到这一点?

If you only store the year, how will you sort on Month and Date? 如果仅存储年份,那么如何对月份和日期进行排序? Instead, store the full datetime object or split out the full date into three fields. 而是,存储完整的datetime对象或将完整的日期分为三个字段。 As already mentioned, these would normally be Char fields, but can be Int and can be converted back to date to sort and compare/diff. 如前所述,这些通常是Char字段,但可以是Int字段,可以转换回最新日期以进行排序和比较/比较。 See: 看到:

How to convert integer into date object python? 如何将整数转换为日期对象python?

Or simply store the full date natively and then get the chunks you need from it as you need it. 或者直接在本地存储完整日期,然后根据需要从中获取所需的数据块。 You might check out the Pendulum Package which opens up a lot more options on date operations. 您可能会签出Pendulum软件包 ,该软件包在日期操作上打开了更多选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django - 需要只能处理年,月或月值的日期时间字段 - Django - Need datetime fields that can handle only year, or year and month values 如何在不命中数据库的情况下使用延迟字段创建django模型实例? - How can I create a django model instance with deferred fields without hitting the database? 如何使用django上传文件时创建年/月/日结构 - how to create year/month/day structure when uploading files with django 如何仅更新Django模型表单中的某些字段? - How can I update only certain fields in a Django model form? 如何在当前年份,django中查询当前年份的对象 - How can i query for objects in current year , current month in django Django:创建模型时如何更新相关模型字段 - Django: How to update related model fields when creating model Django 与用户具有一对一关系的客户 - 创建用户时如何为该 model 创建字段? - Django Customer with onetoone relationship with User - how to create the fields for that model when creating User? 如何在模型中为dateField的月份/年份创建django-filter自定义过滤器? - How to create django-filter custom filter for month/year for a dateField in model? 当生日存储为年/月/日字段时,如何在Django中按年龄从数据库中查询 - How to query from the DB by age in Django when birthday is stored as year/month/day fields Django DateField 只有月份和年份 - Django DateField with only month and year
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM