我有一个词典应用程序,其中的单词(词条)可以 Select 由其他单词组成.在我的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
我想返回两个查询集:
- 所有复合动词:在self.Components和where self.pos.Term="verb"中具有值的词条
- 复合动词的所有唯一成分都是名词:引理是某个其他引理的self.Component_Set()的值,并且本身具有self.pos.Term="noun".
我想使用视图将这两个列表传递给一个模板.
我可以很容易地获得查询集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()
方法按引文形式按字母顺序对该列表进行排序.
有没有更好的方法来返回QuerySet对象?