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'

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Works great with Extract. Thank you very much for your help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.