'Calculate property with request data in Django

I have class Feedback in models in my django project. It has some charField, IntegerField.. and also custom property.

Hovewer what I need is to have a property calculated from input value (from request query params from URL). It means that it is calculated by each request.

My goal is to provide this calculated property with all attributes and other properties of object feedback on list view via Rest Framework.

class Company(CalculatedSummaryModel):
    name = models.CharField(max_length=40, unique=True)
    @property
    def feedbacks(self):
        return Feedback.objects.all()

    def get_lookback_period(self, params):
        try:
            period = int(params['days'])
        except:
            period = 0
        return period
    
    
class CompanyView(viewsets.ModelViewSet):
    queryset = Company.objects.all()
    serializer_class = CompanySerializer

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        lookback_period = instance.get_lookback_period(request.query_params)
        setattr(instance, 'lookback_period', lookback_period)
        serializer = self.get_serializer(instance)
        return Response(serializer.data)
    
    
class CompanySerializer(serializers.HyperlinkedModelSerializer):
    model = Company
    departments = serializers.HyperlinkedRelatedField(many=True, queryset=Department.objects.all(),view_name="department-detail")
    period = serializers.CharField(source='get_lookback_period')

    class Meta(BasicSerializer.Meta):
        model = Company
        fields = ['url', 'name','feedbacks', 'departments', 'period']

What I need is to create field as period and then filter from all feedbacks based on this period and do some other calculations. The lookback period is not static, but dynamic from url (query parameters). So how can I add value from model method into serializer and display it in get request in API? URL example : ..company?lookback_period=5

enter image description here

Thx for your advice.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source