Django:提取不适用于DateTimeField

时间:2019-11-26 06:19:52

标签: python mysql django django-orm django-annotate

如果我使用Extract,则Django ORM的DateTimeField函数在注释后返回 None 。为什么?

models.py

class SimpleModel(models.Model):
    date_value = models.DateField()
    datetime_value = models.DateTimeField()

settings.py

DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'testdb',
            'USER': 'root',
            'PASSWORD': 'password',
        }
    }

Django shell输出[已连接到MYSQL]

In [5]: from django.db.models.functions import  Extract                                                                                               

In [6]: annotate_kwargs = dict(month_from_datetime_field=Extract('datetime_value','month'),month_from_date_field=Extract('date_value','month'))                   

In [7]: SimpleModel.objects.annotate(**annotate_kwargs)[0].__dict__                                                                                   
Out[7]: 
{'_state': <django.db.models.base.ModelState at 0x7fbb8ffb3eb8>,
 'id': 1,
 'date_value': datetime.date(2019, 11, 26),
 'datetime_value': datetime.datetime(2019, 11, 26, 6, 9, 14, tzinfo=<UTC>),
 'month_from_datetime_field': None,
 'month_from_date_field': 11}

0 个答案:

没有答案