Skip to content

Conversation

@rmosquera-bjumper
Copy link

With this small change we can use the NestedHyperlinkedRelatedField with models that doesn't has a relation field between them. I don't know how to create a test demonstrating the use case; any help is welcome.

For example, in this case:

class Item:
  name = models.CharField(max_length=10)

class Doc:
  name = models.CharField(max_length=10)

class Attachment:
  item = models.ForeignKey(Item, on_delete=models.CASCADE)
  doc =  models.ForeignKey(Item, on_delete=models.CASCADE)

If we want to have an URL like /item/1/doc/123, we can do that with:

class ItemDocumentsViewSet(
    mixins.ListModelMixin,
    mixins.CreateModelMixin,
    mixins.DestroyModelMixin,
    viewsets.GenericViewSet,
):
    serializer_class = ItemDocumentSerializer

    def __init__(self, **kwargs):
        self.item_id = None
        super().__init__(**kwargs)

    def initialize_request(self, request, *args, **kwargs):
        request = super().initialize_request(request, *args, **kwargs)
        self.item_id = kwargs.get("item_id")
        return request

   # ....

class ItemDocumentSerializer(HyperlinkedModelSerializer):
    url = NestedHyperlinkedIdentityField(
        view_name="item-documents-detail",
        lookup_url_kwarg="id",
        parent_lookup_kwargs={"item_id": "item_id"},
    )
    
    class Meta:
        model = Doc
        fields = ("url", "name")
    

@rmosquera-bjumper rmosquera-bjumper marked this pull request as ready for review November 12, 2025 16:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant