Search code examples
pythondjangoapidjango-rest-frameworksaas

Django REST Framework How to Efficiently Filter Calculate Model property


I have a model property of is_expired that simply returns True or False by comparing the current time with another field called Saas_expire_date.

 @ property
    def is_expired(self):
        current_time = timezone.now()
        return current_time > self.saas_expire_date

How do i efficiently filter this.. I fear That using For loops will drastically affect response time especial if there is alot of data

class StorePublicAPI(APIView):
    """
    Store API for client side
    """

    def get(self, request):
        """
        `Get Stores`
        """
        raw_stores = Store.objects.filter(
            is_approved=True, is_active=True)
        stores = []
        for store in raw_stores:
            if not store.is_expired:
                stores.append(store)

        serializer = StorePublicSerializer(stores, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

or can you help me if finding a more effective way of calculating whether a user has paid or not? when the Saas_expire_date field reaches the current date time


Solution

  • You are actually doing a time filter for the saas_expiry_date field in your is_expired property. Why not do it also in filter?

    class StorePublicAPI(APIView):
        """
        Store API for client side
        """
    
        def get(self, request):
            """
            `Get Stores`
            """
            current_time = timezone.now()
            queryset = Store.objects.filter(
                is_approved= True,
                is_active=True,
                saas_expire_date__lt=current_time,
            )
    
            serializer = StorePublicSerializer(queryset, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)