優化查詢我有以下的模型結構:Django的ORM:涉及到許多一對多的關係
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())
這導致一噸分貝命中(每個通用的記錄,這涉及到一個容器),所以這顯然是沒有辦法的辦法去做吧。現在,它可能,也許,可以通過獲取SpecificX直接做對象:
s = Specific1.objects.filter(cont__name='somename')
# This gets me all Specific1 objects for the specified container
...
# do it for every Specific type
這樣的數據庫將再次爲每個特定類型(可以接受的,我猜)被擊中。
我知道,.select_related()不適用於m2m關係,因此在這裏沒有多大幫助。
重申,最終結果必須是SpecificX對象的集合(非泛型)。
在反思,這個問題似乎有點毫無意義的我,現在的我已經提供了唯一可能的答案。畢竟,沒有辦法從任意字段的許多表中獲得聯合結果集。好吧,顯然,這是一種方式,但它很醜,涉及動態sql和/或「select *」。我認爲。 – shylent 2009-10-29 12:39:47
您的問題在這裏的確與優化ManyToMany關係無關,並且與優化多表繼承的查詢無關。這確實是一個難題。 – 2009-10-29 14:30:22
現在我想起來了,讓我相信這個問題是關於M2M關係的,事實上,select_related並不會遍歷多對多的關係。 – shylent 2009-10-29 19:08:46