简体   繁体   English

如何在 django 中传递多个可选的 URL 参数?

[英]How to pass multi optional URL parameters in django?

How to pass multi optional URL parameters?如何传递多个可选的 URL 参数?

For example I want pass 2 params: my_color and my_year , but they are optional, so may be none of them will be passed, may be both, or may be only one.例如,我想要传递 2 个参数: my_colormy_year ,但它们是可选的,因此可能不会传递它们中的任何一个,可能两者都传递,或者可能只有一个。

Currently in urls.py I have :目前在urls.py我有:

urlpatterns = [
    re_path(r'^products/(?P<my_color>.*)/(?P<my_year>.*)$', some_view),
]

This obviously is not correct and works only if both of them are passed.这显然是不正确的,只有当它们都通过时才有效。

What would be correct solution?什么是正确的解决方案?

PS I found answers when only one optional parameter needs to be pass, but not figured out how to do same for few parameters. PS 当只需要传递一个可选参数时,我找到了答案,但不知道如何对少数参数执行相同的操作。 Also it seems "multiple-routes option" is not solution in this case (?)在这种情况下,“多路由选项”似乎也不是解决方案(?)

If myyear is a sequence of digits , and mycolor is a equence of non-digits , you can use如果myyear是一个数字序列,而mycolor是一个非数字序列,则可以使用

urlpatterns = [
    re_path(r'^products/((?P<my_color>\D+)/)?(?P<my_year>\d+)$', some_view),
]

this will pass an empty string for the corresponding elements if the my_color or my_year are not present.如果my_colormy_year不存在,这将为相应的元素传递一个空字符串 You thus can write a view that looks like:因此,您可以编写一个如下所示的视图:

def some_view(request, my_color, my_year):
    if my_color:
        # …
    if my_year:
        # …

If both have the same sequence of characters, this is not possible , since how would you interpret products/bla ?如果两者具有相同的字符序列,这是不可能的,因为您将如何解释products/bla Is bla the color, or the year? bla是颜色还是年份?

That being said, I think you make it too complicated.话虽如此,我认为你把它说得太复杂了。 You can define four patterns, for example:您可以定义四种模式,例如:

urlpatterns = [
    path(r'^products/', some_view),
    path(r'^products/<int:year>/'),
    path(r'^products/<str:color>/'),
    path(r'^products/<str:color>/<int:year>/', some_view),
]

Here you thus define four views for the same view.因此,您可以在此处为同一视图定义四个视图。 The view can then define optional parameter:然后视图可以定义可选参数:

def some_view(request, color=None, year=None):
    # …

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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