我有一个具有以下内容的模型:
class TeamInvite(models.Model):
inviter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='invites_sent')
invitee = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='invites_received')
team = models.ForeignKey(Team, related_name='team_invites')
guid = models.UUIDField(default=uuid.uuid4)
class UserMetaData(models.Model):
user = AutoOneToOneField(settings.AUTH_USER_MODEL, related_name='usermetadata')
guid = models.UUIDField(default=uuid.uuid4)
我试图通过仅返回Django Rest Framework中的guid字段来模糊用户的序列化。这是我的第一次尝试,但它似乎无法正常工作
class InviteListingField(serializers.RelatedField):
def to_representation(self, value):
return value.usermetadata.guid
class TeamInviteSerializer(serializers.ModelSerializer):
lookup_field = 'guid'
inviter = InviteListingField(read_only=True)
invitee = InviteListingField(read_only=True)
class Meta:
model = TeamInvite
fields = ('guid', 'inviter', 'invitee', 'team'
)
问题1:我只希望将这种特殊的序列化应用于GET(详细信息)和List调用。
问题2:我是否以正确的方式区分邀请者和被邀请者?因为似乎当我进入to_representation方法时,值两次都是一样的。
答案 0 :(得分:0)
1)您可以通过覆盖ViewSet上的get_serializer_class
来提供每个方法的序列化程序,如下所示:
def get_serializer_class(self):
if self.action == 'retrieve':
return CreateSerializer
else:
return super().get_serializer_class()
2)您可以从子对象映射serialiezr字段,如下所示:
class TeamInviteSerializer(serializers.ModelSerializer):
lookup_field = 'guid'
inviter = UUIDField(read_only=True, source='inviter.guid')
invitee = UUIDField(read_only=True, source='invitee.guid')