Populate Month Based on Date Field in Django

2019-09-10 14:28发布

问题:

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

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.

回答1:

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)

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

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"

You can use the property like so:

import datetime.date as dt

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

print(p.Month)