0

一般的な関係によってリンクされた 2 つのモデルがあります。

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)

そして今、「コードが「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 を別のクエリで取得する

4

1 に答える 1

0

あなたはそのようにすることはできません... その場合に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')
于 2011-10-14T10:03:13.353 に答える