我有两个相互关联的模型。
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)
我有一个常见问题查询集。
faq_list = FAQ.objects.filter(user=user).exclude(answer="").exclude(question="").exclude(category=None)
如何获取faq_list中表示的唯一FAQCategory实例的查询集?
faq_category_list = FAQCategory.objects.filter( ...appear in faq_list... )
谢谢!
答案 0 :(得分:1)
一种简单的方法是在第一个查询中获取pk数组,然后在下一个查询中使用它
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)
但是两次查询数据库的结果都不被接受
所以最好使用Q对象并执行一个查询
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)
))
答案 1 :(得分:0)
# 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)
答案 2 :(得分:0)
我知道了
faq_category_list = FAQCategory.objects.filter(faq__in=faq_list)