Search code examples
djangodjango-rest-frameworkuuid

ID which consists of slug and uuid Django Rest Framework


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')

Solution

  • 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 %}