【问题标题】:Difficult queryset for prefetch预取的困难查询集
【发布时间】:2019-10-16 16:18:33
【问题描述】:

我有模型:

class Inote(IDeclaration):

    Time = models.DateTimeField(auto_now=True)
    Author = models.ForeignKey(User, related_name='%(class)ss')

    __unicode__ = lambda s: str(s.id) + ' (%s)'%(s._meta.model_name)


class Article(Inote):

    Title = models.CharField(max_length=50)

模型通过多表继承链接。在我看来,我尝试通过用户查询集中的 prefetch_related 获取文章:

class UserList(ListView):
    model = User

    def get_queryset(self):

        qs = super(UserList, self).get_queryset().prefetch_related('inotes__article')

        for q in qs:
            for i in q.inotes.all():
                if hasattr(i,'article'):
                    print i.article

        return qs 

如果我将prefetch_related('inotes__article') 应用于qs,我大致得到了我想要的——三个查询:

  1. 从“auth_user”中选择•••
  2. SELECT ••• FROM "testapp_inote" WHERE "testapp_inote"."Author_id" IN ('1', '2', '3', ...)
  3. SELECT ••• FROM "testapp_article" INNER JOIN "testapp_inote" ON ("testapp_article"."inote_ptr_id" = "testapp_inote"."id") WHERE "testapp_article"."inote_ptr_id" IN ('1', '2 ', '3', '4')

但是我不知道innote是什么文章,在这方面我用if hasattr(i,'article')来区分它。我想通过 Prefetch 解决这个问题,但是如果我这样做:

    prefetch = Prefetch("inotes", Inote.objects.filter(article__isnull=False))

    qs = super(UserList, self).get_queryset().prefetch_related(prefetch)

然后我对我的数据库中的每个 inote 有很多查询。

然后我尝试了Prefetch("inotes__article", Inote.objects.filter(article__isnull=False),但在inotes__article 上有FieldError。

如何正确使用 Prefetch 来解决我的问题。在这种情况下,您能否分享有关复杂查询的示例或链接?

谢谢

【问题讨论】:

  • 在您的情况下,对于(简单)查询集,只需使用 django_polymorphic

标签: django django-queryset


【解决方案1】:

您还需要在article 上使用select_related 将文章加入您预取的inotes。我的意思:

prefetch = Prefetch("inotes", Inote.objects.select_related('article').filter(article__isnull=False))
...

这样,当您在if hasattr(i,'article'): 期间访问它时,Django 不需要获取article

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    相关资源
    最近更新 更多