DRF build url dynamically for serializer

Django -- Posted on Sept. 12, 2024

DRF build url dynamically for serializer

              
                from django.urls import reverse

class UrlSerializerMixin:
    
    def get_url(self, obj):
        app = self.Meta.model._meta.app_label
        model = self.Meta.model.__name__.lower()
        if obj.pk:
            # Use the request object to build an absolute URL
            request = self.context.get('request')
            return request.build_absolute_uri(reverse(f'{app}:{model}-detail', args=[obj.pk]))
        return None
                  
   
            

Related Posts