Question

I have two models:

class Organization(models.Model):
    name = models.CharField(max_length=64)

class OrgUser(User):
    organization = models.ForeignKey(Organization, related_name='users')
    role = models.CharField(max_length=1, choices=USER_TYPE_CHOICES)

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = OrgUser
        depth = 1
        fields = ('email', 'role', 'organization',)

class OrganizationSerializer(serializers.HyperlinkedModelSerializer):
    users = USerSerializer(many=True)
    class Meta:
        model = Organization
        depth = 1
        fields = ('name', 'users',)

I'm using the Django REST Framework and I'm trying to get the following output for the given URLS:

GET /organization/

{
    'name':'Hello World',
    'users':[{ 'email':'test@gmail.com', 'role':'A' }]
}

GET /user/

{
    'email':'test@gmail.com',
    'role':'A',
    'organization':{ 'name':'Hello World' }
}

So what's happening is GET /organization/ is giving me the users array and the organization information again.

I've been racking my brain setting the depth property on my serializer, but I can't figure it out for the life of me. If someone could please point me in the right direction, I'd greatly appreciate it.

Was it helpful?

Solution

The problem is that you want different output from your UserSerializer depending on if it's being used alone (i.e. at GET /user/) or as a nested relation (i.e. at GET /organization/).

Assuming you want different fields in both, you could just create a third Serializer to use for the nested relationship that only includes the fields you want in the OrganizationSerializer. This may not be the most elegant way to do it, but I can't find any alternatives.

Sample code:

class Organization(models.Model):
    name = models.CharField(max_length=64)

class OrgUser(User):
    organization = models.ForeignKey(Organization, related_name='users')
    role = models.CharField(max_length=1, choices=USER_TYPE_CHOICES)

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = OrgUser
        depth = 1
        fields = ('email', 'role', 'organization',)

class OrganizationUserSerializer(serializers.HyperlinkedModelSerializer): # New Serializer
    class Meta:
        model = OrgUser
        depth = 1
        fields = ('email', 'role',)

class OrganizationSerializer(serializers.HyperlinkedModelSerializer):
    users = OrganizationUserSerializer(many=True) # Change to new serializer
    class Meta:
        model = Organization
        depth = 1
        fields = ('name', 'users',)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top