我有一个Django模型,如下所示:
class Team(models.Model):
name = models.CharField(max_length=100, unique=True)
managers = models.ManyToManyField(User, through=MgrToTeam, related_name='mng')
users = models.ManyToManyField(User, through=UsrToTeam,related_name='usr')
我现在有一个序列化器,在这里我需要显示与团队相关的所有用户和经理:
class TeamDetailSerializer(serializers.ModelSerializer):
managers = serializers.SlugRelatedField(queryset=User.objects.all(), slug_field='name')
users = serializers.SlugRelatedField(queryset=User.objects.all(), slug_field='name')
class Meta:
model = Team
fields = ['id', 'name', 'managers', 'users']
但是,这给用户和管理员都提供了相同的输出。我该如何解决?
答案 0 :(得分:2)
我很好奇您为什么要使用SlugRelatedField
。假设您确实有某种UserSerializer
,这样做对您有用吗?
class TeamDetailSerializer(serializers.ModelSerializer):
managers = UserSerializer(many=True)
users = UserSerializer(many=True)
class Meta:
model = Team
fields = ['id', 'name', 'managers', 'users']