Home > Back-end >  How to filter the django queryset based on the hours?
How to filter the django queryset based on the hours?

Time:07-19

Serializer

class MyModelSerializer(serailizers.ModelSerializer):
        hour = serializers.SerializerMethodField()

        def get_hour(self, obj):
           created_at = obj.created_at # datetime
           now = datetime.now()
           return (now - datetime).total_seconds() // 3600
         
        class Meta:
           model = MyModel
           fields = "__all__"

API

In the api there will be a filter parameter hr. If it provided for e.g 4 then I should return only the matching entries which has hour 4(calculated in the above serializer).

How can I do this ?

    @api_view(["GET"])
    def get_list(request):
        qs = MyModel.objects.all()
        hr = request.GET.get("hr")
        if hr:
            qs = qs.filter(created_at__hour=hr) # get_hour value = hr this should be the comparison
        return MyModelSerializer(qs, many=True).data 

CodePudding user response:

You can calculate back the two timestamps where in between the number of hours is four, so:

from datetime import timedelta
from django.utils.timezone import now

hr = request.GET.get('hr')
nw = now()
if hr:
    hr = int(hr)
    frm = nw - timedelta(hours=hr 1)
    to = nw - timedelta(hours=hr)
    qs = qs.filter(created_at__range=(frm, to))
# …
  • Related