Grisha S
Grisha S

Reputation: 838

Django REST Framework: Two models nested via a third one (with 2 FKs )

I have two main models in my Django project:

class User(Model):  # let's say this is the built-in User model
    ...

class Thing(Model):
    ...

and I have a helper model defining their relationship:

class ThingUsage(Model):
    user = ForeignKey(User, related_name='thing_usages')
    thing = ForeignKey(Thing, related_name='thing_usages')
    role = CharField()

What would be the best way to set up DRF routing so that I could refer to Things like this:

'/users/{user_pk}/things/'  # for listing
'/users/{user_pk}/things/{thing_pk}'  # for a specific Thing

(which should access all Things that are related to the User via a ThingUsage).

I am guessing that writing my own Router/ViewSet (or whatever else is needed) wouldn't be hard, but I'm wondering if there is a ready-to-use solution (seeing the huge amounts of available DRF extensions).

Upvotes: 2

Views: 807

Answers (1)

Todor
Todor

Reputation: 16050

Using nested routes from drf-extensions, try this:

#inside urls.py
router = ExtendedSimpleRouter()
(
    router.register(r'users', UserViewSet)
          .register(r'things', ThingViewSet, parents_query_lookups=['thing_usages__user'])
)

#inside views.py
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()


class ThingViewSet(NestedViewSetMixin, viewsets.ModelViewSet):
    queryset = Thing.objects.all()

Upvotes: 3

Related Questions