私は次のモデル構造を持っています:
class Container(models.Model):
pass
class Generic(models.Model):
name = models.CharacterField(unique=True)
cont = models.ManyToManyField(Container, null=True)
# It is possible to have a Generic object not associated with any container,
# thats why null=True
class Specific1(Generic):
...
class Specific2(Generic):
...
...
class SpecificN(Generic):
...
Specific
たとえば、特定のコンテナと関係のあるすべてのタイプのモデルを取得する必要があります。
そのためのSQLは多かれ少なかれ些細なことですが、それは問題ではありません。残念ながら、私はORM(特にDjangoのORM)での作業経験があまりないため、ここでパターンが欠落している可能性があります。
ブルートフォース方式で行われる場合、-
c = Container.objects.get(name='somename') # this gets me the container
items = c.generic_set.all()
# this gets me all Generic objects, that are related to the container
# Now what? I need to get to the actual Specific objects, so I need to somehow
# get the type of the underlying Specific object and get it
for item in items:
spec = getattr(item, item.get_my_specific_type())
これにより、大量のdbヒット(コンテナに関連する汎用レコードごとに1つ)が発生するため、これは明らかにそれを行う方法ではありません。これで、おそらく、SpecificXオブジェクトを直接取得することで実行できます。
s = Specific1.objects.filter(cont__name='somename')
# This gets me all Specific1 objects for the specified container
...
# do it for every Specific type
そうすれば、dbは特定のタイプごとに1回ヒットします(許容できると思います)。
.select_related()はm2m関係では機能しないので、ここではあまり役に立ちません。
繰り返しになりますが、最終結果は、(ジェネリックではなく)SpecificXオブジェクトのコレクションである必要があります。