我的模型:
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
}
最佳答案
验证已经在序列化程序之前完成 create
函数,并且由于您尚未使用该 pk 创建 contenthotel,因此 pk 对该字段 (content_hotel) 无效。制作 content_hotel
在 RateHotelSerializer 中只读,问题将得到修复,将序列化器更改为:
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}]
}
关于Django REST Framework 创建嵌套序列化程序会出现 pk 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51974157/