Search code examples
djangodjango-rest-frameworkdjango-rest-framework-gis

Conditionally choose serializer


I have three Django models.

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


class Place(Asset):
  location = PointField()


class Zone(Asset):
  location = PolygonField()

I want to use the same endpoint for Place and Zone. Is it possible to decide for each request which serializer will be used e.g. I could easily check if the requested Asset is a Place or a Zone?

I am only interested in handling a single instance hence there is no need to handle ListView etc.


Solution

  • You can override the get_serializer_class method in your view and add the logic for deciding the correct serializer there.

    As per the 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.

    Code:

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