django 如何过滤某个分类下的文章

2016-11-03 11:50:35 +08:00
 lovebeyondalways

models.py class Category(models.Model): name = models.CharField(verbose_name=u'文章分类', max_length=64)

    def __str__(self):
        return self.name

class article(models.Model):
    title = models.CharField(u'标题', max_length=60)
    category = models.ForeignKey(Category, verbose_name=u'标签', max_length=10, null=True)

在 url 中以分类名作为参数传递给 views 内函数进行过滤行不通

def Category_list(request, category):
    try:
        category_post = article.objects.filter(category_iexact=category)
    except article.DoesNotExist:
        raise Http404
    return render(request, 'category.html', {"category_post": category_post})

ValueError at /linux/ invalid literal for int() with base 10: 'linux'

2579 次点击
所在节点    Python
8 条回复
Blunt1991
2016-11-03 12:10:06 +08:00
```python
def Category_list(request, category):
try:
category_post = article.objects.filter(category__name__iexact=category)
except article.DoesNotExist:
raise Http404
return render(request, 'category.html', {"category_post": category_post})
```
lovebeyondalways
2016-11-03 12:52:38 +08:00
@Blunt1991 谢谢大牛 此法可用
lovebeyondalways
2016-11-03 12:53:30 +08:00
@Blunt1991
敢问大神__name __iexact 这两个字段在哪篇文档里有详解
sherwinkoo
2016-11-03 13:04:10 +08:00
Blunt1991
2016-11-03 13:10:24 +08:00
官方文档, https://docs.djangoproject.com/en/1.10/topics/db/queries/#lookups-that-span-relationships
你原来的代码中 category_iexact 查询时其实是根据 id 去查询的,要根据 model 的其他属性去查询的话,直接双下划线就属性就可以了。
lovebeyondalways
2016-11-03 13:12:32 +08:00
原来是这样,看来官方文档要过一遍
zmrenwu
2016-11-05 19:25:10 +08:00
category_post = article.objects.filter(category=category)

或者 category_post = category.article_set.all()
Ellen
2016-11-21 12:01:58 +08:00
传过来的参数是字符串,这里 iexact 的需要是一个 category 对象。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/317687

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX