我有一个词典应用程序,其中的单词(词条)可以 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

我想返回两个查询集:

  1. 所有复合动词:在self.Components和where self.pos.Term="verb"中具有值的词条
  2. 复合动词的所有唯一成分都是名词:引理是某个其他引理的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对象?

推荐答案

您可以反向查询:

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'
            ).order_by('cf')
        )

然而,你的queryset将是Lemmaduplicate倍,因为有相关的components,因此你可能想要使用.distinct() [Django-doc]来防止这一点.


Note:在Django中,基于类的视图(CBV)通常有一个…View后缀,以避免与模型名称冲突. 因此,您可以考虑将视图类重命名为CompVerbView,而不是CompVerb.

Django相关问答推荐

如果密码在Django中未被散列,则对其进行散列

如何在两个字段上查找 django 模型的副本?

dj_rest_auth 中的 PyTest 警告- RemovedInDjango40Warning: django.conf.urls.url() 已弃用,取而代之的是 django.urls.re_path()

如何在 ModelViewSet 逻辑中读取查询字符串值?

如何在 django 中修改现有模型实例?

使用基于类的 UpdateView 在 Django 中更新用户模型

如何在 django tests.py 中创建管理员用户

django 在 ubuntu 中安装在哪里

Django删除查询集的最后五个以外的所有内容

如何在 Django 测试框架中修改会话

如何在 django-rest-framework 中为 API 使用 TokenAuthentication

Django:创建索引:非唯一,多列

在 django 中是否有生成 settings.SECRET_KEY 的功能?

django 管理员操作而不 Select 对象

如何在 Django 中触发 500 错误?

如何使 Django 的开发服务器公开?

找不到 msguniq.确保您安装了 GNU gettext 工具 0.15 或更新版本. (Django 1.8 和 OSX ElCapitan)

django-getlist()

BASE DIR 的绝对路径是什么?

AttributeError:ManyRelatedManager对象没有add属性?