简体   繁体   中英

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 eg 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 

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))
# …

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM