Jason Howard
Jason Howard

Reputation: 1586

Getting queryset of only related models that appear in another queryset

I've got two models that are related to one another.

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)

I've got a queryset of faqs.

faq_list = FAQ.objects.filter(user=user).exclude(answer="").exclude(question="").exclude(category=None)

How do I get a queryset of the unique FAQCategory instances that are represented in the faq_list?

faq_category_list = FAQCategory.objects.filter( ...appear in faq_list... )

Thanks!

Upvotes: 0

Views: 24

Answers (3)

Jason Howard
Jason Howard

Reputation: 1586

I've figured it out

faq_category_list = FAQCategory.objects.filter(faq__in=faq_list)

Upvotes: 0

Mukul Kumar
Mukul Kumar

Reputation: 2103

# I think you want to get the unique title in FAQCategory model, but for that you don't need to query the database table again. You can get the data from 'faq_list'.

# if you want to have the unique data for title
faq_category_list = list(set([str(fa.category.title) for fa in faq]))

# If you don't want to have the unique data for title in FAQCategory
faq_category_list = [str(fa.category.title) for fa in faq]

print(faq_category_list)

Upvotes: 0

mahyar
mahyar

Reputation: 571

one simple way of doing this is to get array of pks in your first query and use it in the next query like this

faq_list = FAQ.objects.filter(user=user).exclude(answer="").exclude(question="").exclude(category=None).values_list('pk',flat=True) # list of ids

faq_category_list = FAQCategory.objects.filter(faq__id__in=faq_list)

but results querying db two times which is not accepted

so it's better to use Q object and perform one query

from django.db.models import Q

faq_category_list = FAQCategory.objects.filter(faq__user=user, (
       ~Q(faq__answer="") & ~Q(faq__question="") & ~Q(faq__category=None)
))

Upvotes: 1

Related Questions