1

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!

William
  • 3,724
  • 9
  • 43
  • 76

1 Answers1

2

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")
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
  • Hi friend, could you also help me with this relative question? https://stackoverflow.com/questions/51680988/how-to-create-link-for-one-of-the-category-in-django – William Aug 03 '18 at 22:57
  • Hi friend could you help with my latest question:https://stackoverflow.com/questions/51899546/how-to-render-data-to-a-included-a-html-template-in-django – William Aug 17 '18 at 16:27