[Answered ]-Creating Title / Slug based on PK ID

1👍

If you URIs are supposed to look like "example.com/${obj.id}-${sluggify( obj.title )}" then generate these uri when you use them. This uri contains no data that’s not in the DB already, so don’t add it again. The slug’s sole purpose is making url’s look nicer to people and search engines.

Take Stackoverflow as an example: Creating Title / Slug based on PK ID

If you want to select by the slug only, it has to be a Primary Key, unique and immutable. You should be aware that having another PK, the usual id column, would be unneeded.

I don’t say slugs are bad, nor that saving slugs is always bad. There are many valid reasons to save them in the database, but then you need to think about what you’re doing.

Selecting data by their PK (and ignoring the slug) on the other hand requires no thinking, so that should be the default way to go.

1👍

Normally you don’t use the primary key at all. If your concern is just to automatically generate unique slugs (which is the only reason I can see to do what you’re trying to do), then you want an AutoSlugField, which creates a unique slug by increasing an appended number on the slug until it is unique.

There’s an implementation of AutoSlugField which is part of django-command-extensions.

0👍

To name the file based on record ID you have several options:

a) Try to predict ID:

max_pk = self.__class__.objects.aggregate(max_pk=Max('pk'))['max_pk'] or 0
predicted_id = max_pk+1

b) Rename file in post_save when ID is known.

You can also use md5 hash or random strings for generating unique file names.

Btw, there is separate django-autoslug app.

Leave a comment