Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter the django queryset based on the hours?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 

>Solution :

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))
# …
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading