Jason Howard
Jason Howard

Reputation: 1586

queryset based on related model

I've got two models. One (FAQ) is related to the other (FAQCategory). I'm trying to develop a queryset of FAQCategories that are assigned to FAQs, but only if at least one of the FAQs has both the question and answer filled in.

class FAQCategory(models.Model):
    title = models.CharField(max_length=50, null=True, blank=True)       

    def __str__(self):
        return self.title

class FAQ(models.Model):
    category = models.ForeignKey(FAQCategory, on_delete=models.SET_NULL, null=True, blank=True)
    question = models.CharField(max_length=100, null=True, blank=True)
    answer = models.TextField(max_length=10000, null=True, blank=True)

For example, we have 3 FAQCategories

1) General 2) Shipping 3) Warrenty

1) General is not assigned to any faqs. It should not show up in the queryset

2) Shipping is assigned to a FAQ instance, but that FAQ doesn't have an answer on it. Shipping should not show up in the queryset

3) Warrenty is assigned to a FAQ. That FAQ has both an answer and a question value. As a result, Warrenty should appear in the queryset.

How would I write this in django?

Thanks!

Upvotes: 0

Views: 41

Answers (1)

JPG
JPG

Reputation: 88489

Simply,

from django.db.models import Q

exclude_expression = Q(faq__isnull=True) | Q(faq__question__exact="") | Q(faq__answer__exact="")
qs = FAQCategory.objects.exclude(exclude_expression)

References:

Upvotes: 1

Related Questions