0

我正在尝试将类别添加到我的博客中,我有如下模型类。请告诉我是否有任何问题。当用户点击类别时如何显示帖子。先感谢您。

模型.py

class Posts(models.Model):   
    category=models.ForeignKey('indianapp.Category')
    slug = models.SlugField(max_length=100, unique=True)    

    def get_absolute_url(self):
        return ('blog_post_detail', (),{'slug':self.slug,})

    def save(self,*args, **kwargs):
        if not self.slug:
            self.slug=sluggify(self.title)
        super(Posts,self).save(*args,**kwargs)

class Category(models.Model):
    title = models.CharField(max_length=100, db_index=True)
    slug = models.SlugField(max_length=100, db_index=True)
    def __unicode__(self):
        return '%s' % self.title

    @permalink
    def get_absolute_url(self):
        return ('view_by_category', None, { 'slug': self.slug })

视图.py

def view_category(request,slug):
   catego=get_object_or_404(Category,slug=slug)
   category=Category.objects.all()
   posts = Posts.objects.all()
   category_posts = []
   for post in posts:
     if post.category.filter(Posts,slug=slug):
        category_posts.append(post)
   category = Category.objects.filter(slug=slug)
   pagedata.update({'post_list': category_posts})
   return render_to_response('listpage.html',pagedata)

网址.py

url(r'^blog/category/(?P<slug>[^\.]+)','indianapp.views.view_category',name='view_by_category'),

View_category.html

{% block title %}{{ category.title }}{% endblock %}

{% block content %}
{% if post_list %}
    <ul>
    {% for post in post_list %}
        <li><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>There are no posts.</p>
{% endif %}
{% endblock %}
4

1 回答 1

1

你需要的是:

category_posts = category.posts_set.all()

或者

category_posts = Posts.objects.filter(category=category)

我鼓励你阅读 Django 教程。

于 2013-01-17T14:48:48.373 回答