[Fixed]-Django Rest Framework slug_field error

1๐Ÿ‘

โœ…

My guess is DRF does not allow nested attribute lookups on SlugRelatedFields. Simple workaround would be to add a username property on the Profile model and use this in the serializer:

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile')

    @property
    def username(self): 
        return self.user.username

class ClientShareRequest(models.Model):
    checked_by = models.ManyToManyField(Profile, blank=True,
                                            related_name='checked_by')


class ClientShareRequestSerializer(serializers.ModelSerializer):

    checked_by = serializers.SlugRelatedField(
        many=True,
        read_only=True,
        slug_field='username'
    )

    class Meta:
        model = ClientShareRequest
        fields = ('checked_by', )

This works for reads ๐Ÿ™‚

๐Ÿ‘คrtindru

Leave a comment