Đã giải quyết: django chú thích trường ngày giờ thành char

Vấn đề chính là django chú thích trường datetime thành char sẽ không hoạt động với các trường datetime nhất định. Ví dụ: nếu bạn có một trường tên là “created_at” và bạn cố gắng chú thích nó bằng lớp CharField, django sẽ không cho phép bạn lưu dữ liệu của mình.

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>

Ngày giờ ở Django

Django cung cấp một loại ngày giờ thuận tiện có thể được sử dụng để biểu thị ngày và giờ.

Để tạo một đối tượng datetime, hãy sử dụng hàm tạo datetime:

>>> từ django.utils.datetime nhập datetime >>> d = datetime(2015, 11, 25) >>> d 2015-11-25 00:00:00

Ví dụ về mã ngày giờ

Sau đây là danh sách ví dụ mã ngày giờ trong Django.

từ django.utils.datetime nhập datetime từ django.utils.translation nhập gettext_lazy dưới dạng _ từ django.core.urlresolvers nhập ngược lại từ django.db nhập mô hình lớp Người dùng(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): trả về self._first_name + '' + self._last_name + '@' + self._email

bài viết liên quan:

Để lại một bình luận