Reputation: 306
I want to use URL-pattern to fetch product view from my products list. But I came across two methods and a bit confused about which to select.
1)<slug>
2) <int:id>
Upvotes: 2
Views: 7024
Reputation: 20682
Here's the documentation for the url patterns. The two patterns you are comparing are very different:
<slug>
could also be just <something>
. It's just the name of the variable you want to capture, because you didn't include a path converter. By default, this could be any string (excluding the path separator '/'
).<int:id>
specifies two things: A path converter (int
) and the variable name (id
) that you want to capture. In this case, only URLs where this part is integer will match the pattern. id
will always be an integer.If you read the documentation, you'll see that you could also use the slug
path converter, e.g. <slug:slug>
so this will match a subset of strings (ASCII, numbers, hyphens and underscores) and call the captured variable slug
.
The captured variables are passed to your view. So if you want to make a product detail view by passing the product id in the url, you should use <int:id>
and in your view the variable id
can be used to fetch the corresponding product. But if your product model has a slug field and you prefer using that (a slugified version of the product name, e.g. "sweater-men-with-front-logo") then use <slug:slug>
.
Upvotes: 2