有条件地选择序列化器

Conditionally choose serializer

我有三个 Django 模型。

class Asset(models.Model):
  name = models.CharField(max_length=255)


class Place(Asset):
  location = PointField()


class Zone(Asset):
  location = PolygonField()

我想对 Place 和 Zone 使用相同的端点。 是否可以为每个请求决定使用哪个序列化程序,例如我可以轻松检查请求的资产是地点还是区域?

我只对处理单个实例感兴趣,因此不需要处理 ListView 等

您可以在您的视图中重写 get_serializer_class 方法,并在其中添加决定正确序列化程序的逻辑。

根据 DRF docs:

get_serializer_class(self)

Returns the class that should be used for the serializer. Defaults to returning the serializer_class attribute.

May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users.

代码:

class MyView(..):
    ...

    def get_serializer_class(self):
        if asset == place: # here add the logic to decide the asset type
             return PlaceSerializer 
        return ZoneSerializer