chibisov / drf-extensions

DRF-extensions is a collection of custom extensions for Django REST Framework
http://chibisov.github.io/drf-extensions/docs
MIT License
1.47k stars 208 forks source link

Add nested routes to parent serializer #189

Open quantoid opened 7 years ago

quantoid commented 7 years ago

If I have a parent resource that has nested resources, I'd like to include the URLs of the nested resource in the parent resource's serializer output.

For example, if an account can contain a large number of people then I don't want to list all the people in the account (too many), so I create a nested resource for people and want to see that URL in the account records:

> GET https://example.com/api/accounts/123/
< 200 OK {
    "id": 123,
    "url": "https://example.com/api/accounts/123/",
    "name": "example",
    "people": "https://example.com/api/accounts/123/people/"
}

In this case people is a valid field on the Account model, a reverse-lookup on a ForeignKey field on the Person model. But just including a list of all Person URLs in the Account could result in a very large response.

class Account(Model):
    name = CharField(max_length=128)

class Person(Model):
    name = CharField(max_length=64)
    account = models.ForeignKey(
        to=Account,
        related_name='people',
        on_delete=models.CASCADE,
    )

I don't really want to provide a /people resource that can be filtered by account because I want all access to people to go via a specific account.