python - Django where in queryset 在 url 中用逗号分隔 slug

标签 python django

我有一个帖子模型

models.py

class Category(models.Model):
    title = models.CharField(max_length=100,null=True,blank=False)
    slug = models.SlugField(max_length=150,null=True,blank=False)

class Post(models.Model):
    title = models.CharField(max_length=256,null=True,blank=False)
    categories = models.ManyToManyField(Category)

因此,鉴于我需要查询具有特定类别的所有帖子,例如 这是网址http://example.com/?category=slug1,slug2http://example.com/?category=1,2 - 将使用PK或slug

views.py

class PostList(TemplateView):
    ...
    def get(self,request,*args,**kwargs):
        categories = request.GET.get('category')
        post_list = Post.objects().filter(categories__in=categories)
    ...

由于传递逗号分隔的字符串,上述 View 会抛出错误,因为以 10 为基数的 int() 的文字无效:',',但我该如何实现这一点呢?

最佳答案

用逗号分隔,您必须手动执行此操作:

categories = request.GET.get('category').split(',')

更多 Django 方法可以做到这一点,因此将您的查询字符串更改为

?category=slug1&category=slug2

然后你可以使用

categories = request.GET.getlist('category')

关于python - Django where in queryset 在 url 中用逗号分隔 slug,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40100341/

相关文章:

python - 如何在每次发生事件时创建一个新的屏幕实例

python - 强制 Django 显示英语作为后备

python - 模型中 ugettext 的用途

python - Django 查询集 : All Model1 objects where a Model2 exists with a model1 AND the given user

python - 使用 mysql 数据库配置 apache 超集

python - 在 python 中精确 sleep

python - 在 Django 中显示图形/图表

python - Python 中的菱形继承(钻石问题) : Call method from all parent classes

Python - 类似 PHP 的动态数组

python - 将列值分组到字典中