2011-05-05 41 views
0

我有一个非常奇怪的问题,我有一个查询集与自身连接,当我试图访问父记录信息使用[n]它的工作原理,当我通过它循环doesn'吨。那有意义吗?下面是我的例子django模型不能访问父子记录

>>> a=Main.objects.select_related('main', 'parent').filter(list__is_active=True, maini18n__language='en', list__listi18n__language='en') 
>>> a[10]._parent_cache.id 
2L 
>>> for i in a: 
... print i._parent_cache.id 
... 
Traceback (most recent call last): 
    File "<console>", line 2, in <module> 
AttributeError: 'NoneType' object has no attribute 'id' 

回答

1

这里没有神秘。并非所有对象都有父项:项目10有,但有些(包括第一项)则不。访问相关项目之前,您可能需要检查i.parent_id

此外,请注意,_parent_cache是一个实现细节:您应该真的通过i.parent访问相关对象。

+0

优秀的解释,我只是试了一下,并完美地工作:) – 2011-05-05 18:03:23

+0

非常感谢你 – 2011-05-05 18:03:30

+0

我在这里发布了另一个问题http://stackoverflow.com/q/5889751/145277关于在select语句中包含内部连接表。如果你能帮我解决这个问题,我会很感激,你似乎很了解django-models的方式。 – 2011-05-05 18:06:46