daveslab daveslab - 3 months ago 14
Python Question

How to include related resource with Django Rest Framework JSON API?

I am using Django Rest Framework JSON API to create a REST API. I am trying quite simply to include a related resource (2nd degree relation) but Django keeps responding with the error:

This endpoint does not support the include parameter for path...


The structure is something like this:

# models:

class Household(models.Model):
...

class HouseholdMember(models.Model):
household = models.ForeignKey(Household)
...

class Subscription(models.Model):
subscriber = models.ForeignKey(HouseholdMember)
...

# serializers

from rest_framework_json_api import serializers

class SubscriptionSerializer(serializers.ModelSerializer):
class Meta:
model = Subscription


I would like to be able to make a request like this:
http://example.com/api/subscriptions?include=subscriber.household
to be able to group subscriptions by household. However, I simply cannot find out how to do this. I know I need to play around with
ResourceRelatedField
but I'm missing something or too much of a newbie to understand how this works. Any help?

Answer

Well, perhaps I was missing something obvious (because this wasn't mentioned in the documentation), but if you look at the serializers.pyfile in the example directory of the source of Django Rest Framework JSON API, it looks like you need to have a variable called included_serializers to do what I wanted. For my example, here's what you would need:

# models:

class Household(models.Model):
  ...

class HouseholdMember(models.Model):
  household = models.ForeignKey(Household)
  ...

class Subscription(models.Model):
  subscriber = models.ForeignKey(HouseholdMember)
  ...

# serializers

from rest_framework_json_api import serializers

class HouseholdSerializer(serializers.ModelSerializer):
  class Meta:
    model = Household

class HouseholdMemberSerializer(serializers.ModelSerializer):
  included_serializers = {
    'household': HouseholdSerializer
  }

  class Meta:
    model = HouseholdMember

class SubscriptionSerializer(serializers.ModelSerializer):
  included_serializers = {
    'subscriber': SubscriberSerializer
  }

  class Meta:
    model = Subscription
Comments