Home > OS >  Django How do I check that a choices field is not blank in a filter
Django How do I check that a choices field is not blank in a filter

Time:03-09

I have a choices field that can be blank

   review_comment = models.CharField(max_length=60, choices=REVIEW_COMMENT_CHOICES, blank=True)

I now want to filter by review_comment!=blank e.g.

return self.filter(active=True, review_comment!=blank)

How can I achieve this?

CodePudding user response:

Because your CharField don't have null setting so default there won't allow null value to be saved. Also Django discourage using null filter on CharField and TextField https://docs.djangoproject.com/en/dev/ref/models/fields/#null

For filtering out the blank string you can use exclude as chaining query

return self.filter(active=True).exclude(review_comment="")

CodePudding user response:

Is this the answer that you are looking for?

return self.filter(active=True, review_comment__isnull=False)

https://docs.djangoproject.com/en/4.0/ref/models/querysets/#isnull

CodePudding user response:

I have found through this question that the way to check if a value is blank is to use the exclude

So in my case I did this return self.filter(active=True).exclude(review_comment__exact='')

  • Related