Django中的多态序列化对象

w46czmvw  于 2023-03-04  发布在  Go
关注(0)|答案(1)|浏览(127)

我有以下对象继承模型:

class Room:
    name = models.CharField(db_index=True, unique=True, max_length=255)
    status = models.CharField(default=RoomStatus.ACTIVE, max_length=256, null=True)
    members = models.ManyToManyField(User)
    last_activity = models.DateTimeField(default=timezone.now)

继承的模型为:

class LeagueRoom(Room):
    league = models.ForeignKey(League, on_delete=models.CASCADE, null=True)
    location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True)
    logo_url = models.CharField(max_length=1024, null=True)

以及:

class ClubRoom(Room):
    club = models.ForeignKey(Club, on_delete=models.CASCADE, null=True)
    location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True)
    logo_url = models.CharField(max_length=1024, null=True)

各个序列化程序如下所示:

class RoomSerializer(serializers.ModelSerializer):
    members = UserSerializer(read_only=True, many=True)

    class Meta:
        model = Room
        fields = ('id', 'name', 'status', 'members', 'created', 'modified', 'last_active')

以及

class LeagueRoomSerializer(serializers.ModelSerializer):
    location = LocationSerializer(read_only=True)
    league = LeagueSerializer(read_only=True)
    room = RoomSerializer(read_only=True)

    class Meta:
        model = LeagueRoom
        fields = ('id', 'name', 'location', 'status', 'league',
                  'logo_url', 'room', 'created', 'modified',)

以及:

class ClubRoomSerializer(serializers.ModelSerializer):
    location = LocationSerializer(read_only=True)
    club = ClubSerializer(read_only=True)
    room = RoomSerializer(read_only=True)

    class Meta:
        model = ClubRoom
        fields = ('id', 'name', 'location', 'club', 'logo_url',
                  'status', 'room', 'created', 'modified',)

我的问题是,我以下面的方式为一个用户获取了所有房间。

rooms = user.room_set.order_by('-last_activity')

现在我想根据房间类型序列化这个数据。因此,我想遍历房间列表,而不是使用RoomSerializer。如果房间是ClubRoom,则使用ClubRoomSerializerLeagueRoomSerializer。我如何从父对象中确定子对象?

qv7cva1a

qv7cva1a1#

class RoomSerializer(serializers.Serializer):
    def to_representation(self, instance):
        if isinstance(instance, LeagueRoom)
            serializer_class = LeagueRoomSerializer
        elif isinstance(instance, ClubRoom):
            serializer_class = ClubRoomSerializer
        return serializer_class(instance=instance).data

queryset = user.room_set.order_by('-last_activity')
serialized = RoomSerializer(queryset, many=True).data

相关问题