[英]Django: How To Pass Only Selected Arguments Through URL
I am trying to create a search page where buttons can be clicked which will filter the posts like in this page [Splice Sounds][2] (i think you need an account to view this so ill add screenshots).我正在尝试创建一个可以单击按钮的搜索页面,该页面将过滤此页面中的帖子 [Splice Sounds][2](我认为您需要一个帐户才能查看此内容,因此请添加屏幕截图)。
To do this i think i need to pass a list so that i can filter by that list but i can't find a way to do this.为此,我认为我需要传递一个列表,以便我可以按该列表进行过滤,但我找不到这样做的方法。
having a GET
form for each genre (which is being created by a for loop) would allow me to filter by one genre at a time but i want to filter by multple genres at once so that won't work每种类型都有一个GET
表单(由 for 循环创建)可以让我一次过滤一种类型,但我想一次过滤多种类型,这样就行不通了
in the site that i linked to: they pass the genres/tags into the url so how could i do this in django?在我链接到的网站中:他们将流派/标签传递到 url 那么我怎么能在 django 中做到这一点?
Also: i could make seperate url paths and link to those but then i would have to do this for every combination of genres/tags which would be too much so i can't do that.另外:我可以制作单独的 url 路径并链接到这些路径,但是我必须为每种类型/标签的组合都这样做,这太多了,所以我不能这样做。
the link shows a site which passes tags through url like this https://splice.com/sounds/search?sound_type=sample&tag=drums,kicks该链接显示了一个通过 url 传递标签的站点,例如https://splice.com/sounds/search?sound_type=sample&tag=drums,kicks
here is some relevant code:这是一些相关的代码:
this is how i want to filter which is why i need to pass a list of args这就是我想要过滤的方式,这就是为什么我需要传递 args 列表
for arg in args:
Posts = Posts.filter(genres=arg)
urls网址
urlpatterns = [
path('', views.find, name='find'),
path('searchgenres=<genres_selected>', views.find_search, name='find_search'),
]
EDIT: I have tried this many ways such as using ajax but i couldn't get that to work well编辑:我尝试了很多方法,例如使用 ajax 但我无法让它正常工作
EDIT 2: i have changed the question to How To Pass Only Selected Arguments Through URL编辑 2:我已将问题更改为如何仅通过 Arguments 通过 URL
To pass a list into a request you could:要将列表传递到请求中,您可以:
If you obtain the request as a list, you could use Post.objects.filter(genre__in=genres)
.如果您以列表的形式获取请求,则可以使用Post.objects.filter(genre__in=genres)
。
It might also be helpful to know that Django allows for complex lookups with Q objects from django.db.models import Q
.知道 Django 允许使用from django.db.models import Q
的 Q 对象进行复杂查找也可能会有所帮助。 The |
该|
character represents OR.字符代表 OR。 This allows complex filtering.这允许复杂的过滤。 For instance: Posts.objects.filter(Q(genre='Pop') | Q(genre='Rock') | Q(genre='Jazz'))
例如: Posts.objects.filter(Q(genre='Pop') | Q(genre='Rock') | Q(genre='Jazz'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.