Question

I want to refer to some instance of a data through my URL. What is the recommended way to do that? Should I use the primary key of that data or is that exposing database information unnecessarily? Even with using PKs, the URL is not 'clean'. So how do you handle this usually?

Details:

I use django for my website. I have a model called 'Team'. Any teacher can create her own Team online at which point it gets added to the database. I do not require the Team name to be unique. A teacher can have multiple teams.

Now any action "add students to the team", "assign homework to the team" anything, requires that a reference to the team should be passed in the URL. Something like:

 {{ SITE_URL }}/add-student/{{ team }}/

Since names are non-unique, I cannot use the name.

Currently, I assign a UUID to every team when it is created and use the uuid in my URLs. That works, but it makes for ugly URLs.

I could use primary key of the team, which would be shorter than the uuid, but again not a very nice URL. I also wonder whether exposing primary key of a model's database entry is a security issue? Though, I noticed that SO seems use primary keys in its URLs.

So what is the best practice here?

Was it helpful?

Solution

Django's class based views (DetailView, UpdateView) default to using the pk in the url as a named url group to determing which object to fetch, so judging by that i think it doesn't violate any practices by using the pk in the url.

If you want a very memorable url you could create a slug and append the pk, while not perfectly optimal, would still be more memorable then a UUID

I also believe, your view should be validating whether the requesting user has the correct permissions to view the url, this should be independent of the actual url structure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top