简体   繁体   中英

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).

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

in the site that i linked to: they pass the genres/tags into the url so how could i do this in 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.

the link shows a site which passes tags through url like this 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

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

EDIT 2: i have changed the question to How To Pass Only Selected Arguments Through URL

To pass a list into a request you could:

  1. Use html checkboxes and in views aggregate them into a list
  2. Use a single textbox and parse in views

If you obtain the request as a list, you could use 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 . The | character represents OR. This allows complex filtering. For instance: Posts.objects.filter(Q(genre='Pop') | Q(genre='Rock') | Q(genre='Jazz'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM