Solved: django annotate datetime field to char

The main problem is that django annotate datetime field to char will not work with certain datetime fields. For example, if you have a field called “created_at” and you try to annotate it with the CharField class, django will not allow you to save your data.


I have a model with a datetime field and I want to annotate it to a charfield. I tried this:
but it gives me an error: <code>Cannot resolve keyword 'CharField' into field.</code>


You can use <code>Func</code>:  and then use the <code>.format()</code> method on the resulting string to format it however you want (e.g., YYYY-MM-DD):  .  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)     

Datetime in Django

Django provides a convenient datetime type that can be used to represent dates and times.

To create a datetime object, use the datetime constructor:

>>> from django.utils.datetime import datetime >>> d = datetime(2015, 11, 25) >>> d 2015-11-25 00:00:00

Examples of datetime code

The following is a list of example datetime code in Django.

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 + ‘@’ + self._email

Related posts:

Leave a Comment