已解决:django 将日期时间字段注释为 char

主要问题是 django 将日期时间字段注释为 char 不适用于某些日期时间字段。 例如,如果您有一个名为“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 提供了一种方便的日期时间类型,可用于表示日期和时间。

要创建日期时间对象,请使用日期时间构造函数:

>>> 从 django.utils.datetime 导入日期时间 >>> d = datetime(2015, 11, 25) >>> d 2015-11-25 00:00:00

日期时间代码示例

以下是 Django 中的示例日期时间代码列表。

从 django.utils.datetime 导入 datetime 从 django.utils.translation 导入 gettext_lazy as _ 从 django.core.urlresolvers 导入反向 从 django.db 导入模型类 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): 返回 self._first_name + ' ' + self._last_name + '@' + self._email

相关文章:

发表评论