简体   繁体   English

如何根据小时过滤 django 查询集?

[英]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 API

In the api there will be a filter parameter hr .在 api 中会有一个过滤器参数hr If it provided for eg 4 then I should return only the matching entries which has hour 4(calculated in the above serializer).如果它提供了例如 4,那么我应该只返回具有 4 小时的匹配条目(在上面的序列化程序中计算)。

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:您可以计算两个时间戳之间的小时数为 4,因此:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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