【问题标题】:When to use slug field and query string何时使用 slug 字段和查询字符串
【发布时间】:2015-11-20 06:54:07
【问题描述】:

我是 django 网络开发的新手,我不知道何时使用 slug 字段以及何时在 url 中使用查询字符串参数。谁能建议我它们之间的实际区别。

【问题讨论】:

标签: python django django-urls slug


【解决方案1】:

在 slug 相关的 django url 中,您有一个与视图关联的 url。但是您不能将查询字符串参数传递给您的视图。

Ex -example.com/post/hello-world/ 不会将任何参数传递给您的视图函数。

但是如果你想给你的视图传递额外的参数,例如,

example.com/search/?q=hello-world

这里的q=hello-world 是传递给您的视图的查询字符串参数。 在您的视图函数中,您可以在request.GET 中获取这些参数 所以你的视图函数是这样的

def helloworld():
    qParams = request.GET.get('q', '')
     ....
     ....

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    使用 slug 可以使 url 保持简单和干净,从而易于记忆。考虑以下示例:

    example.com/post/hello-world/
    

    v/s

    example.com/?post=hello-world
    

    显然,第一个更干净。

    但查询字符串参数也有其用途。例如,当您搜索对象时。

    example.com/search/?q=hello-world
    

    或者当你需要传递多个参数时

    example.com/search/?q=hello+world&lang=en&something=else
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多