繁体   English   中英

查询集上的 Django 过滤不起作用

[英]Django filtering on a queryset not working

我正在尝试根据条件在现有查询集上添加过滤器,但它不起作用。

这有效

        queryset = None
        if self.is_instructor == True:
            queryset = Issue.objects.filter(type=self.type, type_id=self.type_id).filter(status__in=self.status)
        else:    
            queryset = Issue.objects.filter(type=self.type, type_id=self.type_id, created_by=self.created_by)

这不

        queryset = None
        if self.is_instructor == True:
            queryset = Issue.objects.filter(type=self.type, type_id=self.type_id)
        else:    
            queryset = Issue.objects.filter(type=self.type, type_id=self.type_id, created_by=self.created_by)
        
        if len(self.status) > 0:
            queryset.filter(
                    Q(status__in=self.status)
                )

        queryset.order_by('-created_on')

这就是我的模型的样子

STATUS_CHOICES = (
    ('UNC', 'Unconfirmed'),
    ('CNF', 'Confirmed'),
    ('INP', 'In Progress'),
    ('UAC', 'User Action Pending'),
    ('RES', 'Resolved'),
)

class Issue(models.Model):
    UNCONFIRMED = 'UNC'

    title = models.CharField(max_length=512, blank=False)
    description = models.TextField(blank=False)

    created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='creator')
    created_on = models.DateTimeField(auto_now_add=True)

    status = models.CharField(
        max_length=3,
        choices=STATUS_CHOICES,
        default=UNCONFIRMED
    )

放心, self.status 包含所需的数据。 我不能使用 get() 因为有多个记录

我已经看到了其他一些答案,但无法取得进展。 提前致谢。

巴桑特

您需要更新query_set而不仅仅是调用该函数。

...
if len(self.status) > 0:
    queryset = queryset.filter(status__in=self.status)

queryset = queryset.order_by('-created_on')

暂无
暂无

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

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