ઉકેલાયેલ: django એનોટેટ datetime ફીલ્ડ to char

મુખ્ય સમસ્યા એ છે કે જેંગો એનોટેટ ડેટટાઇમ ફીલ્ડ ટુ ચાર ચોક્કસ ડેટટાઇમ ફીલ્ડ સાથે કામ કરશે નહીં. ઉદાહરણ તરીકે, જો તમારી પાસે “created_at” નામનું ફીલ્ડ છે અને તમે તેને CharField ક્લાસ સાથે ટીકા કરવાનો પ્રયાસ કરો છો, તો જેંગો તમને તમારો ડેટા સાચવવાની મંજૂરી આપશે નહીં.

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 માંથી તારીખ સમય આયાત કરો 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 + '@' + સ્વ._email

સંબંધિત પોસ્ટ્સ:

પ્રતિક્રિયા આપો