주요 문제는 django annotate datetime 필드를 char로 지정하면 특정 datetime 필드에서 작동하지 않는다는 것입니다. 예를 들어 "created_at"라는 필드가 있고 CharField 클래스로 주석을 달려고 하면 django에서 데이터를 저장할 수 없습니다.
field
I have a model with a datetime field and I want to annotate it to a charfield. I tried this:
<code>MyModel.objects.values('date').annotate(date_char=CharField())
</code>
but it gives me an error: <code>Cannot resolve keyword 'CharField' into field.</code>
A:
You can use <code>Func</code>: https://docs.djangoproject.com/en/dev/ref/models/expressions/#func-expressions and then use the <code>.format()</code> method on the resulting string to format it however you want (e.g., YYYY-MM-DD): https://docs.python.org/2/library/string.html#formatstrings . Something like this should work:
<code>from django.db import models # for Func expression class
from django import db # for connection alias, used in Func expression class
# create connection alias, used in Func expression class
# (this is only necessary if you are using multiple databases)
# replace 'default' with your database name if using multiple databases
my_conn = db._connections['default']
# create Func expression object that will convert date to string format YYYY-MM-DD
my_func = models.Func(my_conn, function='TO_CHAR', template='%(function)s(%(expressions)s::DATE, 'YYYY-MM-DD')')
# use my_func in query as follows:
MyModelObjects = MyModelObjects .objects .values('date') .annotate(date_char=my_func)
</code>
Django의 날짜/시간
Django는 날짜와 시간을 나타내는 데 사용할 수 있는 편리한 datetime 유형을 제공합니다.
datetime 객체를 만들려면 datetime 생성자를 사용합니다.
>>> from django.utils.datetime import datetime >>> d = datetime(2015, 11, 25) >>> d 2015-11-25 00:00:00
datetime 코드의 예
다음은 Django의 예제 datetime 코드 목록입니다.
from django.utils.datetime import datetime from django.utils.translation import gettext_lazy as _ from django.core.urlresolvers import reverse from django.db import models class User(models.Model): first_name = models.CharField(max_length=30, blank=True, nullable=False) last_name = models.CharField(max_length=30, blank=True, nullable=False) email = models.EmailField() def __str__(self): return self._first_name + ' ' + self._last_name + '@' + 자기._이메일