I have a function like this:
def eventcateg_detail(request):
ca = EventTypeCategory.objects.values()
for i in range(0, len(ca)):
pk_sub = ca[i]['sub_categ_id']
if (pk_sub!=None):
category = EventTypeCategory.objects.get(id = pk_sub)
category = category.name
return render(request,"events/categ.html",{
'obj': ca
})
Definition of above function:
Fist i am getting a dictionary in ca variable i.e.
[{'Message_slug': u'critical', 'sub_categ_id': None, 'user_id': 1L, 'id': 190L, 'name': u'Critical'}, {'Message_slug': u'information', 'sub_categ_id': 190L, 'user_id': 1L, 'id': 192L, 'name': u'Information'}]
Now i want to get a value defining in sub_categ_id for each content. I got this in pk_sub variable. As you can see that pk_sub is returning an id (which is foreign key to itself). I want to get all these values which pointing to that pk_sub. I am also getting this :
Critical
Information
Amit Pal
Now i want to append this category.name into a list. So that i can easily pass to my template. How should i do this?
I tried by putting following code at next line:
categories = categories.append(category)
but it didn’t work 🙁
Two things:
for category in ca:. In the body of that loop, category will be bound to each item in ca.categories, so you cannot append to it; in any case,list.appendreturnsNone, and destructively modifies the list, so you would have to omit the assignment.Finally, as a matter of style one usually uses
x is not Nonerather than!=when testing for None.Update: Note @agf’s comment, which describes the proper way to use the Django ORM to perform this task.