基于Django中的日期字段填充月份 [英] Populate Month Based on Date Field in Django

查看:498
本文介绍了基于Django中的日期字段填充月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个字段根据之前输入的日期自动生成月份。

I would like to have a field auto-generate the month based on the date entered before it.

models.py

models.py

class Projects(models.Model):
    Name = models.CharField(max_length=100, null=True, blank=False) 
    Date = models.DateField(null=True, blank=False)
    Month = models.CharField(max_length=100, null=True, blank=False)   

        def get_month(self):
            if self.Date:
                self.Month = self.Date.strftime("%B")
                self.save()

我看到这个问题,并尝试了,但似乎没有要发生我失踪了什么我必须创建这些之一吗?谢谢。

I saw this question on SO and tried it out, but nothing seems to be happening. What am I missing? Do I have to create one of these? Thanks.

推荐答案

您可以简单地覆盖 save em> auto-field 而不是以新的方法调用 save

You can simply override your save to add the auto-field instead of calling save in a new method:

class Projects(models.Model):
    Name = models.CharField(max_length=100, null=True, blank=False) 
    Date = models.DateField(null=True, blank=False)
    Month = models.CharField(max_length=100, null=True, blank=False)  

    def save(self, *args, **kwargs):
        if self.Date: 
            self.Month = self.Date.strftime("%B")
        super(Model, self).save(*args, **kwargs)

但是,上述将使 Month 仅在保存实例后可用

But the above will make Month available only after the instance has been saved.

您可以创建一个属性,以便 Month 可从模型的实例获得,并且还可以防止在你的数据库中添加重复的信息:

You can instead create a property, so that Month is available from an instance of the model and also prevent adding duplicate info in your DB:

class Projects(models.Model):
    Name = models.CharField(max_length=100, null=True, blank=False) 
    Date = models.DateField(null=True, blank=False)

    @property
    def Month(self):
        if self.Date:
            return self.Date.strftime("%B")
        return "No date entry"

您可以使用如下属性:

import datetime.date as dt

# import your Projects model
p = Projects(Name='ceuskervin', Date= dt.today())

print(p.Month)

这篇关于基于Django中的日期字段填充月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆