我一直在开发一个项目,用户可以在其中发布帖子并将其放在不同的类别中,我有一个 View 应该显示所有类别中的所有帖子,但它按顺序显示所有类别并且帖子必须以混合所有类别的随机顺序显示。这里的错误是 View 按顺序显示所有类别,例如首先是 Action 类别中的所有帖子,然后是体育类别中的所有帖子(当它应该混合时)。我该如何以混合顺序显示所有类别的所有帖子?
View .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 %}
最佳答案
您可以使用__in
lookup [Django-doc]获取属于任何类别的 Mates
对象:
def matesmain(request):
if request.user.has_posts():
mates = Mates.objects.filter(
<b>categories__in=['action', 'sports']</b>
)
context = {
'mates' : mates
}
return render(request, 'mates.html', context)
else:
# …
然后您可以使用以下方式渲染它们:
{% for <b>mate in mates</b> %}
{{ mate.categories }}
{% endfor %}
您可以使用.order_by('?')
[Django-doc]以随机顺序获取项目:
def matesmain(request):
if request.user.has_posts():
mates = Mates.objects.filter(
categories__in=['action', 'sports']
)<b>.order_by('?')</b>
context = {
'mates' : mates
}
return render(request, 'mates.html', context)
else:
# …
关于python - 如何在一个 django 模板中显示所有类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62842742/