How to get all the post in the same category in Django

我是研究僧i 提交于 2019-12-11 15:14:11

问题


I'm coding a news website.I have 'category' in News model.

Now I want to get all the news in one of the categories named 'opinion'. But get: invalid literal for int() with base 10: 'opinion'

here is part of my News model:

    class News(models.Model):
        category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="cate", blank=True, verbose_name='分类')

here is my Category model:

class Category(models.Model):
    name = models.CharField(max_length=40)  # 分类名

    class Meta:
        verbose_name = "分类"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

here is part of my view:

class NewsView(View):

    def get(self, request):
        opinion_news = News.objects.filter(category="opinion")

        return render(request, 'index.html', {

            'opinion_news': opinion_news,

        })

here is part of my index.html

            {% for opinion in opinion_news %}
            <li class="media">
               <h>{{opinion.title}}</h>
            </li>
            {% endfor %}

Any friend can help?Thank you so much!


回答1:


By default filtering by foreignkey use id field (integer). To use another field of category model use __fieldname syntax. For instance if category model has name field:

opinion_news = News.objects.filter(category__name="opinion")


来源:https://stackoverflow.com/questions/51625049/how-to-get-all-the-post-in-the-same-category-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!