django model cannot access parent child record
I have a very strange problem, I have a queryset that join with itself, when I try to access the p开发者_StackOverflow社区arent record information using a[n] it works, when I loop through it doesn't. Does that make sense? below is my example
>>> 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'
There's no mystery here. Not all the objects have a parent: item 10 does, but some (including the first) don't. You may want to check i.parent_id
before accessing the related item.
Also, note that _parent_cache
is an implementation detail: you should really be accessing the related objects via i.parent
.
精彩评论