Django Rest Framework:在 GET 响应中发送完整的外键对象,但只接受 POST 有效负载中的外来 ID,没有两个序列化程序?
Django Rest Framework: Send full foreign key objects in GET response but accept only foreign ids in POST payload, without two serializers?
假设我有两个模型:
class Singer((models.Model):
name = models.CharField(max_length=200)
class Song(models.Model):
title = models.CharField(max_length=200)
singer = models.ForeignKey(Singer)
还有两个序列化程序:
class SingerSerializer(serializers.ModelSerializer):
class Meta:
model = Singer
fields = '__all__'
class SongSerializer(serializers.ModelSerializer):
singer = SingerSerializer()
class Meta:
model = Singer
fields = '__all__'
我已经按照上面的方式定义了序列化程序,因为我需要在歌曲的 GET 响应中使用完整的外键对象:
{
"singer": {
"id": 1,
"name": "foo"
},
"id": 1,
"title": "foo la la"
}
有没有办法允许 POST/PATCH 有效载荷只发送外部对象的 ID 而不是整个对象,而不需要编写不同的序列化程序?我希望 PATCH 负载是这样的:
{
"singer": 1,
"id": 1,
"title": "foo la la"
}
您可以通过定义 read_only 和 write_only 字段来实现。
此外,通过使用 SlugRelatedField
允许 DRF 从相关模型上的字段自动填充它。
尚未测试此代码,但这个想法仍然有效。
class SongSerializer(serializers.ModelSerializer):
singer = SingerSerializer(read_only=True)
singer_id = serializers.SlugRelatedField(queryset=Singer.objects.all(), slug_field='singer', write_only=True)
class Meta:
model = Singer
fields = ['singer', 'signer_id']
假设我有两个模型:
class Singer((models.Model):
name = models.CharField(max_length=200)
class Song(models.Model):
title = models.CharField(max_length=200)
singer = models.ForeignKey(Singer)
还有两个序列化程序:
class SingerSerializer(serializers.ModelSerializer):
class Meta:
model = Singer
fields = '__all__'
class SongSerializer(serializers.ModelSerializer):
singer = SingerSerializer()
class Meta:
model = Singer
fields = '__all__'
我已经按照上面的方式定义了序列化程序,因为我需要在歌曲的 GET 响应中使用完整的外键对象:
{
"singer": {
"id": 1,
"name": "foo"
},
"id": 1,
"title": "foo la la"
}
有没有办法允许 POST/PATCH 有效载荷只发送外部对象的 ID 而不是整个对象,而不需要编写不同的序列化程序?我希望 PATCH 负载是这样的:
{
"singer": 1,
"id": 1,
"title": "foo la la"
}
您可以通过定义 read_only 和 write_only 字段来实现。
此外,通过使用 SlugRelatedField
允许 DRF 从相关模型上的字段自动填充它。
尚未测试此代码,但这个想法仍然有效。
class SongSerializer(serializers.ModelSerializer):
singer = SingerSerializer(read_only=True)
singer_id = serializers.SlugRelatedField(queryset=Singer.objects.all(), slug_field='singer', write_only=True)
class Meta:
model = Singer
fields = ['singer', 'signer_id']