1 回答

TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊
所以最后我通過RelatedField為每個(gè)外鍵使用而不是單獨(dú)的序列化器解決了這個(gè)問題,除了嵌套EventSerializer的是真正需要編寫嵌套Event對象的。
這是RaceSerializer:
class RaceSerializer(serializers.ModelSerializer):
owner = UserSerializer(read_only=True)
type = TypeField()
country = CountryField()
region = RegionField()
timezone = TimezoneField()
events = EventSerializer(many=True)
race_cal_types = serializers.SerializerMethodField()
def create(self, validated_data):
with transaction.atomic():
events = validated_data.pop('events', None)
race = Race(**validated_data)
race.save()
for event in events:
Event.objects.create(race=race, **event)
return race
這是我在我的每個(gè)字段中使用的組合RelatedField,例如外鍵:ModelSerializerRaceSerializerregion
class RegionSerializer(serializers.ModelSerializer):
class Meta:
model = Region
fields = ('pk', 'name', 'code')
class RegionField(RelatedField):
def get_queryset(self):
return Region.objects.all()
def to_internal_value(self, data):
return self.get_queryset().get(**data)
def to_representation(self, value):
return RegionSerializer(value).data
每個(gè)字段 ( type, region, country, timezone) 都有自己的to_internal_value方法to_representation,可以按照我需要的方式序列化/反序列化數(shù)據(jù)。
添加回答
舉報(bào)