I have a for loop to iterate a list. In every iteration i have a different value, and i want to add this value to my context. I’m trying using context.update, but every time this returns an empty context.
JavaScript
x
18
18
1
def get_context_data(self, **kwargs):
2
context = super(Board_dets_view, self).get_context_data(**kwargs)
3
id_board = self.object.id
4
context['column_list'] = Column.object.filter(board_id=id_board)
5
6
clist = Column.object.values_list('id', flat=True).filter(board_id=id_board)
7
cCard = Card.object
8
print(clist)
9
for i in range(0, clist.count()):
10
print('i=%s',i)
11
12
cCard = Card.object.filter(column_id = clist[i])
13
print('cCard=%s',cCard)
14
context.update({'card_list': cCard})
15
16
print(context)
17
return context
18
cCard returns correct data. The only thing I need is to store what come from cCard to context[‘card_list’], but evert attempt i made, was an empty result.
Advertisement
Answer
Please don’t filter that way. This will produce n+1 queries, one for each Column
. You can retrieve the last of Card
s with:
JavaScript
1
6
1
def get_context_data(self, **kwargs):
2
context = super(Board_dets_view, self).get_context_data(**kwargs)
3
context['column_list'] = Column.object.filter(board=self.object)
4
context['card_list'] = Card.object.filter(column__board=self.object)
5
print(context)
6
return context
You can use two consecutive underscores (__
) to look “through” relations like a ForeignKey
, ManyToManyField
, etc.