我的模特:
class ContentHotel(models.Model):
hotel_id = models.IntegerField(unique=True, blank=True, primary_key=True)
class Meta:
managed = False
db_table = 'content_hotels'
ordering = ('hotel_id',)
def __str__(self):
return str(self.hotel_id)
class RateHotel(models.Model):
rate_hotel_id = models.IntegerField(blank=True, primary_key=True, unique=True)
content_hotel = models.ForeignKey(ContentHotel, on_delete=models.CASCADE, related_name='rate_hotel')
class Meta:
managed = False
db_table = 'rate_hotels'
ordering = ('rate_hotel_id',)
def __str__(self):
return str(self.rate_hotel_id)
我的序列化器:
class RateHotelSerializer(serializers.ModelSerializer):
class Meta:
model = RateHotel
fields = __all__
class ContentHotelSerializer(serializers.ModelSerializer):
rate_hotel = RateHotelSerializer(many=True)
class Meta:
model = ContentHotel
fields = ('hotel_id', 'rate_hotel')
def create(self, validated_data):
rate_hotels = validated_data.pop('rate_hotel')
content_hotel = ContentHotel.objects.create(**validated_data)
for rate_hotel in rate_hotels:
RateHotel.objects.create(content_hotel=content_hotel, **rate_hotel)
return content_hotel
JSON:
{
"hotel_id": -1,
"rate_hotel": [{"content_hotel": -1, "rate_hotel_id": 1}]
}
上面的JSON输入给我这样的错误:
{
"rate_hotel": [
{
"content_hotel": [
"Invalid pk \"1\" - object does not exist."
]
}
],
"status_code": 400
}
参考:http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers
我引用了上面的链接,有人知道如何解决这个问题吗?但是,如果我分别创建两个对象,它可以正常工作,如下所示:
{
"hotel_id": -1,
}
{
"content_hotel": -1,
"rate_hotel_id": 1
}
答案 0 :(得分:2)
验证已在序列化程序create
函数之前完成,并且由于尚未使用该pk创建contenthotel,因此pk对于该字段(content_hotel)无效。在RateHotelSerializer中将content_hotel
设为只读,问题将得到解决,请将序列化器更改为此:
class RateHotelSerializer(serializers.ModelSerializer):
class Meta:
model = RateHotel
fields = __all__
read_only_fields = ('content_hotel', )
并且现在您也不需要在content_hotel
的列表对象中添加rate_hotel
,使用这样的json:
{
"hotel_id": -1,
"rate_hotel": [{"rate_hotel_id": 1}]
}