'Django filtering on a queryset not working

I am trying to add a filter on an existing queryset based on a condition but it doesn't work.

This works

        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)

This doesn't

        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')

This is how my model looks like

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
    )

Assured, self.status holds the required data. I can't use get() because there are multiple records

I have seen some other answers but couldn't make progress. Thanks in advance.

Basant



Solution 1:[1]

You need to update query_set not just call the function.

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

queryset = queryset.order_by('-created_on')

Hope it could help.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Lu