Django Models: error when using DateField as Forei

2019-07-25 18:09发布

Having an issue when trying to use DateField of a model class as the ForeignKey for another model class, and using default set to today on both classes. The error message is:

django.core.exceptions.ValidationError: ["'self.date' value has an invalid date format. It must be in YYYY-MM-DD format."]

code:

class DailyImage(models.Model):
    date = models.DateField(auto_now_add=True, unique=True)
    name = models.CharField(max_length = 1000)
    image = models.CharField(max_length = 1000)
    location = models.CharField(max_length = 1000)

    def __str__(self):
        return str(self.id) + ": " + self.name + ", " + self.location

class JournalEntry(models.Model):
    date = models.DateField(auto_now_add=True)
    journal = models.CharField(max_length = 5000)
    image = models.ForeignKey(DailyImage, to_field='date', default='self.date')

The site is a daily journal. Each day, it adds an image from unsplash.it to the DailyImage class, which is then displayed as the header on the home page, and header on the page for the journal entry created that day. When a journal entry is created, it should automatically be referenced to the image that was created that day.

testing it in shell, the date fields seem to match, but are formatted as: datetime.date(YYYY, MM, DD)

>>> a = JournalEntry.objects.get(pk=1)
>>> a
<JournalEntry: test>
>>> a.date
datetime.date(2016, 11, 7)
>>> from journal.models import DailyImage as image
>>> b = image.objects.get(pk=1)
>>> b.date
datetime.date(2016, 11, 7)
>>> b.date == a.date
True

Any suggestions to how this should be done properly would be greatly appreciated!

1条回答
别忘想泡老子
2楼-- · 2019-07-25 18:32

a.date returns the datetime object, but you have to set the format.

t = datetime.date(2016, 11, 7) 
t.strftime("%Y-%m-%d")
# '2016-11-07'

You could also set the default datetime format in settings.py

DATETIME_FORMAT = 'Y-m-d'

However I'm not sure that would be a solution in your situation.

查看更多
登录 后发表回答