【问题标题】:Django: get ValueQuerySet with values from generic relationDjango:使用通用关系中的值获取 ValueQuerySet
【发布时间】:2011-10-14 08:53:05
【问题描述】:

我有两个通过通用关系链接的模型:

from django.contrib.contenttypes import generic
from django.db import models

class Bar(models.Model):
    content_type   = models.ForeignKey(ContentType)
    object_id      = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()

    code  = models.CharField(max_length=10)
    value = models.IntegerField()

class Foo(models.Model):
    ... base fields ...
    bars = generic.GenericRelation(Bar)

现在我想获取所有'code'为'xxx'的'bar.value',语法如下:

Foo.objects.filter(...foofilters..., bars__code='xxx').values('bars__value')

但这不起作用(Django 告诉我 'bars__value' 不是有效字段)。

有什么提示吗?

编辑: 在 SQL 中,我会做这样的事情:

SELECT bar.value
FROM   foo 
JOIN   django_content_type AS ct
    ON ct.app_label = 'foo_app'
   AND ct.model = 'foo'
JOIN   bar 
    ON bar.content_type_id = ct.id
   AND bar.object_id = foo.id
WHERE  bar.code = 'xxx'

或使用另一个查询获取 content_type_id

【问题讨论】:

    标签: django django-queryset generic-relations


    【解决方案1】:

    你不能那样做......想象一下 sql 在这种情况下应该是什么样子

    你可能需要的是:

    foo_ids = Foo.objects.filter(foo-filters).values_list('id', flat=True) # Getting Foo ids filtered
    Bar.objects.filter(
              content_type=ContentType.objects.get_for_model(Foo),
              object_id__in=foo_ids,
              bar-filters
        ).values('value')
    

    【讨论】:

    • 我对 SQL 的尝试是“SELECT bar.value FROM foo JOIN bar ON bar.foo_id = foo.id WHERE bar.code = 'xxx' AND ...”
    猜你喜欢
    • 2020-12-21
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 2014-12-28
    相关资源
    最近更新 更多