Django Models: error when using DateField as ForeignKey

情到浓时终转凉″ 提交于 2019-12-11 09:16:12

问题


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:


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.



来源:https://stackoverflow.com/questions/40469078/django-models-error-when-using-datefield-as-foreignkey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!