gpt4 book ai didi

python - 如何在 Django 中按类别对主题进行排序?

转载 作者:行者123 更新时间:2023-12-01 09:33:51 25 4
gpt4 key购买 nike

好吧,我想按 Django 中的类别对我的主题进行排序。最好的方法是什么?

views.py:

from django.shortcuts import render
from .models import Category
from .models import Topic
# Create your views here.
def forums(request):
categorys = Category.objects.all()
topics = Topic.objects.all()
return render(request, 'forums.html', {'categorys': categorys, 'topics': topics})

models.py:

from django.db import models

# Create your models here.

class Attachment(models.Model):
file = models.FileField()
def __str__(self):
return self.file
class Category(models.Model):
title = models.CharField(max_length=150)
def __str__(self):
return self.title
class Topic(models.Model):
title = models.CharField(max_length=150)
description = models.TextField()
category = models.ForeignKey('Category', on_delete=models.CASCADE)
def __str__(self):
return self.title
class Post(models.Model):
title = models.CharField(max_length=150)
body = models.TextField()
forum = models.ForeignKey('Topic', on_delete=models.CASCADE)
def __str__(self):
return self.title

另外,是的,我知道类别拼写错误,我仍然需要添加元。

最佳答案

您可以通过以下方式获取类别内的所有主题:

{% for category in categorys %}
<h1>{{category.title}}</h1>
<ul>
{% for topic in category.topic_set.all %}
<li>{{topic.title}}</li>
{% endfor %}
</ul>
{% endfor %}

关于python - 如何在 Django 中按类别对主题进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49709652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com