Filtering objects inside a for loop and put into a list
So I'm trying to get the most recent Posts from the favourited tags of a certain profile and I'm having some problems with it. That's what i'm trying to do:
tags = profile.fav_tags.all()
for tag in tags:开发者_开发问答
s1 |= Post.objects.filter(tags__name__iexact=tag.name).distinct().order_by('-created_date')[:15]
results = chain(s1)
When i run this i get:w Exception Type: UnboundLocalError Exception Value: local variable 's1' referenced before assignment
You need to initialize your s1
variable prior to the loop, probably with empty set:
s1 = set()
for tag in tags:
# ...
精彩评论