1

I want to identify my database items over id which consists of slug and uuid, so if two users add f.e. name of the item: "Mercedes A40", they will be stored in database with different ids f.e. "mercedes-a40-25b6e133" and "mercedes-a40-11ac4431".

What should I type inside my Product model in id field? How can I combine it?

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
slug = models.SlugField(max_length=250, unique_for_date='published')
  • You can not make composite primary keys in Django, just set the primary key as the uuid as you have done, and use it in url patterns such that both the uuid and slug appear. – Willem Van Onsem Aug 22 '21 at 11:07

1 Answers1

3

You can store it with two fields: a UUIDField and a SlugField, and use both in the urls.py.

For example:

urlpatterns = [
    # ...,
    path('<slug:slug>-<uuid:uuid>/', some_view, name='name-of-the-view'),
    # …
]

then in the view, you can retrieve the data with:

from django.shortcuts import get_object_or_404

def some_view(request, slug, uuid):
    object = get_object_or_404(MyModel, slug=slug, id=uuid)
    # …

and for a given object you can convert it to a URL with:

class MyModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    slug = models.SlugField(max_length=250, unique_for_date='published')

    # …

    def get_absolute_url(self):
        return reverse('name-of-the-view', kwargs={'uuid': self.id, 'slug': self.slug})

or in the template with:

{% url 'name-of-the-view' uuid=object.id slug=object.slug %}
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555