django orm: 使用annotate case在prefetch结果上

huangapple go评论58阅读模式
英文:

django orm: use annotate case on prefetch result

问题

这是我的模型的近似副本:

class To(models.Model):
   pass

class FromA(models.Model):
    to = models.ForeignKey(To)

class FromB(models.Model):
    to = models.ForeignKey(To)

是否有办法编写这样的查询?

To.objects.annotate(from=Case(
                            When(froma__isnull=False, then=Prefetch("froma")),
                            When(fromb__isnull=False, then=Prefetch("fromb"))
                    ))

请注意,我已经为你翻译了代码部分,并删除了额外的内容。如果你需要更多帮助,请随时提出。

英文:

this is a near replica of my models:

class To(models.Model):
   pass

class FromA(models.Model):
    to = models.ForeignKey(To)

class FromB(models.Model):
    to = models.ForeignKey(To)

is there a way to write a query like this?

To.objects.annotate(from=Case(
                            When(froma__isnull=False, then=Prefetch("froma")),
                            When(fromb__isnull=False, then=Prefetch("fromb"))
                    ))

答案1

得分: 0

到目前为止,这是我找到的最佳答案。

from django.db.models import Subquery, OuterRef
froma_info = FromA.objects.filter(To=OuterRef('pk')).values('carrot', 'pear', 'apple')[:1]
fromb_info = FromB.objects.filter(To=OuterRef('pk')).values('carrot', 'pear', 'apple')[:1]

to_list = To.objects.annotate(
    from=Case(
        When(froma__isnull=False, then=Subquery(froma_info)),
        When(fromb__isnull=False, then=Subquery(fromb_info)),
        default=Value({
            'carrot': '无可用来源',
            'pear': '',
            'apple': '',
        }),
        output_field=JSONField(),
    )
)

这是您提供的代码的翻译部分。

英文:

so far, this is the best answer I have found.

from django.db.models import Subquery, OuterRef

froma_info = FromA.objects.filter(To=OuterRef('pk')).values('carrot', 'pear', 'apple')[:1]
fromb_info = FromB.objects.filter(To=OuterRef('pk')).values('carrot', 'pear', 'apple')[:1]

to_list = To.objects.annotate(
    from=Case(
        When(froma__isnull=False, then=Subquery(froma_info)),
        When(fromb__isnull=False, then=Subquery(fromb_info)),
        default=Value({
            'carrot': 'No from available',
            'pear': '',
            'apple': '',
        }),
        output_field=JSONField(),
    )
)

huangapple
  • 本文由 发表于 2023年2月6日 02:39:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75354632.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定