我一直在研究一个项目,用户可以在其中发布帖子并将其放在不同的类别中,我的视图应该显示所有类别中的所有帖子,但按顺序显示所有类别并且帖子必须以随机顺序显示,并混合所有类别。这里的错误是视图按顺序显示所有类别,例如,当应该混合操作时,首先是动作类别的所有帖子,然后是体育类别的所有帖子。如何以混合顺序显示所有类别的所有帖子?
views.py
def matesmain(request):
if request.user.has_posts():
action = Mates.objects.filter(categories='action')
sports = Mates.objects.filter(categories='sports')
context = {
'action' : action,
'sports' : sports,
}
print("nice3")
return render(request, 'mates.html', context)
mates.html
{% for act in action %}
{% if act %}
I have the posts from action category here
{% endif %}
{% endfor %}
{% for sprt in sports %}
{% if sprt %}
I have the posts from sports categpry here
{% endif %}
{% endfor %}
答案 0 :(得分:2)
您可以利用__in
lookup [Django-doc]来获得属于任何类别的Mates
对象:
def matesmain(request):
if request.user.has_posts():
mates = Mates.objects.filter(
categories__in=['action', 'sports']
)
context = {
'mates' : mates
}
return render(request, 'mates.html', context)
else:
# …
然后您可以使用以下命令渲染它们:
{% for mate in mates %}
{{ mate.categories }}
{% endfor %}
您可以使用.order_by('?')
[Django-doc]以随机顺序获得物品:
def matesmain(request):
if request.user.has_posts():
mates = Mates.objects.filter(
categories__in=['action', 'sports']
).order_by('?')
context = {
'mates' : mates
}
return render(request, 'mates.html', context)
else:
# …
答案 1 :(得分:1)
一种简单的方法是为每个变量分配另一个变量,然后将新变量传递到上下文中,这将始终对其进行洗牌。
def matesmain(request):
if request.user.has_posts():
action = Mates.objects.filter(categories='action')
new_action = action.order_by('?')
sports = Mates.objects.filter(categories='sports')
new_sports = sports.order_by('?')
context = {
'action' : new_action,
'sports' : new_sports,
}
print("nice3")
return render(request, 'mates.html', context)