Reputation: 1109
I have the following models:
class User(AbstractUser):
...some fields...
relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to')
class Relationship(models.Model):
from = models.ForeignKey(User, related_name='from')
to = models.ForeignKey(User, related_name='to')
type = models.IntegerField()
I have the following User Serializer:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'first_name', 'last_name', ...some fields...)
read_only_field = 'username'
It works great, but now I need to get followers nested with the user. My first attempt was to create a UserBasicSerializer like that:
class UserBasicSerializers(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'first_name', 'last_name')
read_only_field = 'username'
and add the following to User Serializer:
followers = UserBasicSerializers(required=False, many=True, source='to')
However, I get AttributeError: Relationship object has no attribute first_name
Thank you!
Upvotes: 1
Views: 1061
Reputation: 15529
You can see that instead using to
related name, you need to use related_to
, which is pointing to an actual user object (to
is pointing to Relationship
object instead). That's why you get this exception.
With a little help of the following tip: https://stackoverflow.com/a/24216503/1566605, you can display nested users:
class RecursiveField(serializers.Serializer):
def to_native(self, value):
return self.parent.to_native(value)
class UserSerializer(serializers.ModelSerializer):
related_to = RecursiveField(many=True)
class Meta:
model = User
fields = ('id', 'username', 'first_name', 'last_name', 'related_to')
read_only_field = 'username'
Upvotes: 2