【问题标题】:How to remove items from queryset based on condition and then return as json response in django如何根据条件从查询集中删除项目,然后在 django 中作为 json 响应返回
【发布时间】:2021-04-13 02:22:18
【问题描述】:

我正在使用 select_related() 进行连接操作并使用以下代码过滤记录

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

在上面的代码中,是否可以检查查询集中的第一项是否有规则名称字段值为空,如果为空,我需要在 json 响应中返回剩余的查询集项,如果不为空,则返回所有项作为 json 响应。

【问题讨论】:

    标签: python django django-views django-serializer


    【解决方案1】:

    检查第一个元素有什么问题?

    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
    

    你在 timezone.now() 上的过滤器只执行一次:当你的类被定义时。所以对这个方法的任何调用都不应该在类定义中,而是调用每个请求。

    在您的实际实现中, now 将在您启动服务器后立即调用。两周后,过滤器仍将在同一日期。

    【讨论】:

    • 精确度:您需要覆盖 get_queryset(self),而不是直接覆盖查询集。
    • 没错,我什至没有阅读请求...已编辑以清理此内容。
    • @NicolasAppriou 它工作得很好,你能解释一下“如果 first_item 不是 None 并且不是 first_item.rulename:”这行代码是做什么的吗?我只需要检查 first_item 是否有 rulename 字段为空或空。如果为空或null,需要忽略queryset的第一项
    • 如果查询集不包含任何项目,'first' 方法返回 None。所以你需要确保你有第一个项目。当 first_item 为 None 时尝试访问 first_item.rulename 将引发 AttributeError
    • 好的,这很清楚。所以我需要在 if 循环中另外添加 first_item.rulename !== '' 或 first_item.rulename !== None 来验证我的条件对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多