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.
def get_context_data(self, **kwargs):
context = super(Board_dets_view, self).get_context_data(**kwargs)
id_board = self.object.id
context['column_list'] = Column.object.filter(board_id=id_board)
clist = Column.object.values_list('id', flat=True).filter(board_id=id_board)
cCard = Card.object
print(clist)
for i in range(0, clist.count()):
print('i=%s',i)
cCard = Card.object.filter(column_id = clist[i])
print('cCard=%s',cCard)
context.update({'card_list': cCard})
print(context)
return context
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.
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:
def get_context_data(self, **kwargs):
context = super(Board_dets_view, self).get_context_data(**kwargs)
context['column_list'] = Column.object.filter(board=self.object)
context['card_list'] = Card.object.filter(column__board=self.object)
print(context)
return context
You can use two consecutive underscores (__
) to look "through" relations like a ForeignKey
, ManyToManyField
, etc.