【发布时间】: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