在django中还有其他传递查找参数的方法吗



我正试图将查找参数传递给我的views.py以呈现到模板

型号.py

class Category(models.Model):
name = models.CharField(max_length=20)
slug = models.SlugField(max_length=200, blank=True, unique=True)
class Post(models.Model):
""""
created_on = models.DateTimeField(auto_now_add=True)
cover = models.ImageField(null=True, blank=True )
categories = models.ManyToManyField(Category, related_name='posts', blank=True)

views.py

def index_category(request, category):
posts = Post.objects.filter(categories__name__contains=category).order_by('-created_on')
context = {
"category": category,
"posts": posts,
}
return render(request, "blog/index_category.html", context)

index_category.html

{% extends "base.html" %}
{% block content %}
<div class="col-md-8 offset-md-2">
<h1>{% block title %}{{ category | title }}{% endblock title %}</h1>
<hr>
{% for post in posts %}
<h2><a href="{% url 'index-detail' post.slug %}">{{ post.title }}</a></h2>
<small>
{{ post.created_on.date }} |&nbsp;
Categories:&nbsp;
{% for category in post.categories.all %}
<a href="{% url 'blog-category' category.name %}">
{{ category.name }}
</a>&nbsp;
{% endfor %}
</small>
<p>{{ post.body | slice:":200" }}...</p>
{% endfor %}
</div>
{% endblock %}

当我在类别页面上刷新localhost时,除了块标题外,它什么也不返回。

有没有其他方法可以过滤帖子和类别之间的多对多关系???

为了避免将来出现类似category名称的问题,请更改以下内容:

posts = Post.objects.filter(categories__name__contains=category).order_by('-created_on')

到关系调用:(您在Post.category字段中有related_name='posts'(

category = Category.objects.get(name__iexact=category)
posts = category.posts.all().order_by('-created_on')

有关更多帮助,请显示urls.py

如何将category变量传递到函数index_category中?

最新更新