我有一个字典应用程序,其中单词(引理)可以选择由其他单词组成。在我的
models.py
中,这看起来像:
class Lemma(models.Model):
cf = models.CharField(max_length=200) #citation form
pos = models.ForeignKey(Pos, on_delete=models.CASCADE) #part of speech
components = models.ManyToManyField("self", symmetrical=False, blank=True) #component Lemma
我想返回两个查询集:
我想使用视图将这两个列表传递给模板。
我能够很容易地获得查询集 1,但是我对查询集 2 的解决方案都非常复杂。我的
views.py
中的相关课程如下所示:
class CompVerb(generic.ListView):
model = Lemma
queryset = Lemma.objects.filter(
Q(pos__term="verb") & ~Q(components=None)
).order_by("cf") #queryset 1, compound verbs
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
nouns = self.queryset.values_list("components")
nouns = set([Lemma.objects.get(pk=l[0]) for l in nouns])
nouns= [l for l in nouns if l.pos.term == "noun"]
context["nouns"] = nouns #queryset 2, nouns that are components of compound verbs
return context
这也为我的
verbs
变量留下了一个常规列表,而不是一个正确的查询集,我可以在其中使用 .order_by()
方法按引文形式对这个字母顺序列表进行排序。
是否有更好的方法可以返回查询集对象?
可以反向查询:
class CompVerb(generic.ListView):
model = Lemma
queryset = Lemma.objects.filter(
~Q(components=None), pos__term='verb'
).order_by(
'cf'
) # queryset 1, compound verbs
def get_context_data(self, **kwargs):
return super().get_context_data(
**kwargs,
nouns=Lemma.objects.filter(lemma__in=self.queryset, pos__term='noun')
)
您的
queryset
将会重复Lemma
很多次,因为有相关的components
,因此您可能需要使用.distinct()
[Django-doc]来防止这种情况.