【问题标题】:Django rest framework: name 'Serializer' not definedDjango rest框架:未定义名称'Serializer'
【发布时间】:2020-08-04 11:57:07
【问题描述】:

我有两个具有一对多关系的模型,我想序列化两端的相关字段。

模型:

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)

序列化器:

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',)

我该如何解决这个问题?我知道我创建了一个循环依赖项,因为两个序列化程序相互依赖。

有没有更好的方法?

【问题讨论】:

  • 我想说,即使您可能会遇到 maximum recursion depth exceeded 异常。建议重新定义任一序列化程序并放入其他序列化程序。
  • 是的,我想了很多。但我想不出另一种定义序列化程序的方法

标签: django django-rest-framework


【解决方案1】:

作为我在 OP 中的评论的扩展,在 ServiceSerializer 类之前创建一个新的序列化程序类 Mechanic 模型

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',)

【讨论】:

  • 谢谢...我最终也这样做了
  • 递归将是无限的,因此您别无选择。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多