0

Hello StackOverflow community,

I am currently struggling with specifying an output format in my views.py. I have a column "date" which is using following format: 2021-01-14. In my response, I would like to change the date format so that it only shows the year 2021.

I already tried it with Cast but it seems like this is not the right approach. For this view, I do not use a Serializer, hence adding it there would not be an option.

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})

What I tried:

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})

Error message

TypeError: __init__() got an unexpected keyword argument 'format'

DevDjas
  • 59
  • 2
  • 7

1 Answers1

1

You should use Extract/ExtractYear database function instead

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.

iklinac
  • 14,944
  • 4
  • 28
  • 30