தீர்க்கப்பட்டது: django annotate datetime field to char

முக்கிய பிரச்சனை என்னவென்றால், django annotate datetime field to 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.utils.datetime இலிருந்து இறக்குமதி தேதிநேரம் >>> d = தேதிநேரம்(2015, 11, 25) >>> d 2015-11-25 00:00:00

தேதி நேரக் குறியீட்டின் எடுத்துக்காட்டுகள்

ஜாங்கோவில் உள்ள டேட் டைம் குறியீட்டின் உதாரணம் கீழே உள்ளது.

django.utils.datetime இலிருந்து django.utils.translation இலிருந்து தேதிநேரத்தை இறக்குமதி செய்க 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 + 'st_name. + '@' + self._email

தொடர்புடைய இடுகைகள்:

ஒரு கருத்துரையை