在Django中对对象进行多态序列化

时间:2018-11-08 23:51:34

标签: python django django-orm

我有以下对象继承模型。

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,请使用ClubRoomSerializer或其他LeagueRoomSerializer。 我不确定如何从父对象确定子对象。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

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