Django将动态URL参数传递给reverse函数

huangapple go评论55阅读模式
英文:

Django passing dynamic URL parameter into reverse function

问题

我刚开始学习Django。到目前为止,我将动态URL参数传递给get_absolute_url()方法内的reverse函数的方式如下:

# 通过kwargs使用:
def get_absolute_url(self):
    return  reverse('book-detail', kwargs={'id': self.id})

# 或者通过args使用:
def get_absolute_url(self):
    return reverse('book-detail', args=[self.id])

# 但我发现有一些示例使用以下代码:
def get_absolute_url(self):
    return reverse('book-detail', args=[str(self.id)])

我已经使用简单的图书库应用程序将图书的id传递到URL中,以获取图书详细信息。这三种变体都可以正常工作,没有任何问题。有人能解释一下为什么以及何时应该使用args=[str(self.id)]吗?

英文:

I have just stated to learn Django. So far I pass dynamic URL parameters into reverse function inside the get_absolute_url() method in the following ways:

# By using kwargs:
def get_absolute_url(self):
    return  reverse('book-detail', kwargs={'id':self.id})

# Or by using the args:
def get_absolute_url(self):
    return reverse('book-detail', args=[self.id])

# But I found several examples of the following code:
def get_absolute_url(self):
    return reverse('book-detail', args=[str(self.id)]

I have used the simple library app to pass id of the book into URL in order to get book details. All three variants work fine without any problem. Can somebody explain to me why and when we should use args=[str(self.id)]?

答案1

得分: 0

Using args=[str(self.id)] works because you are not using self.id as an int when you create a URL via reverse(), but as part of the string that makes up a URL. The Reverse function actually converts it to a (urlescaped) string as part of its process.

So you never actually have to use str(), it's redundant as it already happens later in the process, but it won't break anything either.

英文:

Using args=[str(self.id)] works because you are not using self.id as an int when you create a URL via reverse(), but as part of the string that makes up a URL. The Reverse function actually converts it to a (urlescaped) string as part of its process.

So you never actually have to use str(), it's redundant as it already happens later in the process, but it won't break anything either.

huangapple
  • 本文由 发表于 2023年2月10日 02:30:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75402953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定