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'
1
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}) ``` |
2
lovebeyondalways OP @Blunt1991 谢谢大牛 此法可用
|
3
lovebeyondalways OP @Blunt1991
敢问大神__name __iexact 这两个字段在哪篇文档里有详解 |
4
sherwinkoo 2016-11-03 13:04:10 +08:00
|
5
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 的其他属性去查询的话,直接双下划线就属性就可以了。 |
6
lovebeyondalways OP 原来是这样,看来官方文档要过一遍
|
7
zmrenwu 2016-11-05 19:25:10 +08:00
category_post = article.objects.filter(category=category)
或者 category_post = category.article_set.all() |
8
Ellen 2016-11-21 12:01:58 +08:00
传过来的参数是字符串,这里 iexact 的需要是一个 category 对象。
|