好吧,我想按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
另外,是的,我知道类别拼写错误,我仍然需要添加Meta。
答案 0 :(得分:1)
您可以通过以下方式获取类别中的所有主题:
{% for category in categorys %}
<h1>{{category.title}}</h1>
<ul>
{% for topic in category.topic_set.all %}
<li>{{topic.title}}</li>
{% endfor %}
</ul>
{% endfor %}