我有三个Django模型。
class Asset(models.Model):
name = models.CharField(max_length=255)
class Place(Asset):
location = PointField()
class Zone(Asset):
location = PolygonField()
我想对“位置”和“区域”使用相同的端点。是否可以为每个请求决定将使用哪个序列化程序,例如,我可以轻松地检查所请求的资产是场所还是区域?
我只对处理单个实例感兴趣,因此无需处理ListView等。
您可以在视图中覆盖该get_serializer_class
方法,并在其中添加用于确定正确的序列化器的逻辑。
根据DRF文档:
get_serializer_class(self)
返回应该用于序列化程序的类。默认为返回serializer_class属性。
可以重写以提供动态行为,例如使用不同的序列化程序进行读写操作,或为不同类型的用户提供不同的序列化程序。
代码:
class MyView(..):
...
def get_serializer_class(self):
if asset == place: # here add the logic to decide the asset type
return PlaceSerializer
return ZoneSerializer
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句