1

I want to get each single item from my database by a id combine of slug and uuid. In my model I have:

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

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

In my view I am using ModelViewSet:

class ProductList(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

    def get_object(self, queryset=None, **kwargs):
        item = self.kwargs.get('pk')
        return generics.get_object_or_404(Product, id=item)

    def get_queryset(self):
        return Product.objects.all()

In my urls I am using router:

from rest_framework.routers import DefaultRouter
from .views import ProductList

app_name = 'products'

router = DefaultRouter()
router.register('', ProductList, basename='product')
urlpatterns = router.urls

How can I customize it so I can get not just the self.kwargs.get('pk') but also the slug from the link.

I mean that I want to have links to each iteam like this: "item-name-25b6e133" and "item-name-11ac4431", where the first part is the slug and the second is the uuid. The slug should be automatically created of name field by the POST request.

Using path it would look like this:

urlpatterns = [
    path('<slug:slug>-<uuid:uuid>/', some_view, name='name-of-the-view'),
]
  • 1
    [This](https://stackoverflow.com/questions/21365906/rest-calls-with-multiple-lookup-fields-for-reverse-lookup) might help – Brian Destura Aug 23 '21 at 00:29

0 Answers0