Django rest framework: name 'Serializer' not defined

Viewed 856

I have two models which have one to many relationship and I want to serialize the related fields on both ends.

The models:

class Mechanic(models.Model):
    name = models.CharField('Name', max_length=256)
    status = models.CharField('Status', choices=constants.MECHANIC_STATUS, default=constants.MECHANIC_STATUS[0][0],
                              max_length=64)
    current_lat = models.CharField('Current Latitude', max_length=64)
    current_lng = models.CharField('Current Longitude', max_length=64)

    def __str__(self):
        return self.name


class Service(models.Model):
    type = models.CharField('Service Type', choices=constants.SERVICE_TYPES,
                            default=constants.SERVICE_TYPES[0][0], max_length=64)
    mechanic = models.ForeignKey(Mechanic, on_delete=models.CASCADE, related_name='services')
    vehicle_type = models.CharField('Vehicle Type', choices=constants.VEHICLE_TYPES,
                                    default=constants.VEHICLE_TYPES[0][0], max_length=64)
    charges = models.IntegerField('Charges')

    def __str__(self):
        return "{}, {}".format(self.mechanic, self.type)

The serializers:

class ServiceSerializer(serializers.ModelSerializer):
    mechanic = MechanicSerializer(read_only=True) # Throws an error

    class Meta:
        model = Service
        fields = ('id', 'type', 'mechanic', 'vehicle_type', 'charges')


class MechanicSerializer(serializers.ModelSerializer):
    services = ServiceSerializer(many=True, read_only=True)

    class Meta:
        model = Mechanic
        fields = ('id', 'name', 'status', 'services', 'current_lat', 'current_lng')
        read_only_fields = ('id',)

How do I approach this problem? I understand that I've created a cyclic dependency because both serializers depend on each other.

Is there a better way to do it?

1 Answers

as an extenstion to my comment in the OP, create a new serializer class of Mechanic model before the ServiceSerializer class

class MechanicShortSerializer(serializers.ModelSerializer):
    class Meta:
        model = Mechanic
        fields = '__all__'


class ServiceSerializer(serializers.ModelSerializer):
    mechanic = MechanicShortSerializer(read_only=True) # replace with new serializer

    class Meta:
        model = Service
        fields = ('id', 'type', 'mechanic', 'vehicle_type', 'charges')


class MechanicSerializer(serializers.ModelSerializer):
    services = ServiceSerializer(many=True, read_only=True)

    class Meta:
        model = Mechanic
        fields = ('id', 'name', 'status', 'services', 'current_lat', 'current_lng')
        read_only_fields = ('id',)
Related