简体   繁体   中英

How to remove items from queryset based on condition and then return as json response in django

I am doing join operation using select_related() and filtering records using below code

class ActiveclientViewSet(viewsets.ModelViewSet):
 queryset = Ruledefinitions.objects.select_related('pmdclinicalruleid').filter(pmdclinicalruleid__effectivedate__lt = timezone.now(),pmdclinicalruleid__retireddate__gt = timezone.now())
 serializer_class = RuledefinitionsSerializer

In the above code, is it possible to check whether the first item from queryset has rulename field value as empty and if it is empty i need to return remaining queryset items in json response if not empty return all items as json response.

What's wrong with checking the first element?

class ActiveclientViewSet(viewsets.ModelViewSet):
    queryset = Ruledefinitions.objects.select_related('pmdclinicalruleid')
    serializer_class = RuledefinitionsSerializer

    def get_queryset(self):
        now = timezone.now
        queryset = super().get_queryset().filter(
            pmdclinicalruleid__effectivedate__lt=now,
            pmdclinicalruleid__retireddate__gt=now,
        )
        first_item = queryset.first()
    
        if first_item is not None and not first_item.rulename:
            queryset = queryset[1:]

    return queryset

Your filter on timezone.now() is only executed once: when your classe is defined. So any call to this method should not be in the classe definition, but called every request.

In your actual implementation, now would be called as soon as you start the server. Two weeks later, the filter would still be at the same date.

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