Django Rest Framework:更改查询集中带注释字段的输出格式
Django Rest Framework: changing output format of annotated field in queryset
你好 Whosebug 社区,
我目前正努力在 views.py 中指定输出格式。我有一列“日期”,它使用以下格式:2021-01-14。
在我的回复中,我想更改日期格式,以便它只显示年份 2021.
我已经用 Cast 试过了,但似乎这不是正确的方法。
对于这个视图,我不使用序列化器,因此添加它不会有一个选项。
views.py
class FilterParams(generics.ListAPIView):
model = Variants
queryset = Variants.objects.all()
def get(self, request, *args, **kwargs):
queryset = self.get_queryset()
ModelsByYears = queryset.values('model').distinct().annotate(min_year=Min('date')).annotate(max_year=Max('date')).order_by('model')
return Response(data= {'ModelsByYears':ModelsByYears})
我试过的:
class FilterParams(generics.ListAPIView):
model = Variants
queryset = Variants.objects.all()
def get(self, request, *args, **kwargs):
queryset = self.get_queryset()
ModelsByYears = queryset.values('model').distinct().annotate(min_year=Min(Cast('date', DateTimeField(format="%Y")))).annotate(max_year=Max('date')).order_by('model')
return Response(data= {'ModelsByYears':ModelsByYears})
错误信息
TypeError: __init__() got an unexpected keyword argument 'format'
您应该改用 Extract
/ExtractYear
数据库函数
Takes an expression representing a DateField, DateTimeField,
TimeField, or DurationField and a lookup_name, and returns the part of
the date referenced by lookup_name as an IntegerField. Django usually
uses the databases’ extract function, so you may use any lookup_name
that your database supports.
你好 Whosebug 社区,
我目前正努力在 views.py 中指定输出格式。我有一列“日期”,它使用以下格式:2021-01-14。 在我的回复中,我想更改日期格式,以便它只显示年份 2021.
我已经用 Cast 试过了,但似乎这不是正确的方法。 对于这个视图,我不使用序列化器,因此添加它不会有一个选项。
views.py
class FilterParams(generics.ListAPIView):
model = Variants
queryset = Variants.objects.all()
def get(self, request, *args, **kwargs):
queryset = self.get_queryset()
ModelsByYears = queryset.values('model').distinct().annotate(min_year=Min('date')).annotate(max_year=Max('date')).order_by('model')
return Response(data= {'ModelsByYears':ModelsByYears})
我试过的:
class FilterParams(generics.ListAPIView):
model = Variants
queryset = Variants.objects.all()
def get(self, request, *args, **kwargs):
queryset = self.get_queryset()
ModelsByYears = queryset.values('model').distinct().annotate(min_year=Min(Cast('date', DateTimeField(format="%Y")))).annotate(max_year=Max('date')).order_by('model')
return Response(data= {'ModelsByYears':ModelsByYears})
错误信息
TypeError: __init__() got an unexpected keyword argument 'format'
您应该改用 Extract
/ExtractYear
数据库函数
Takes an expression representing a DateField, DateTimeField, TimeField, or DurationField and a lookup_name, and returns the part of the date referenced by lookup_name as an IntegerField. Django usually uses the databases’ extract function, so you may use any lookup_name that your database supports.