Django-rest:发送 POST 带有 2 个外键的请求
Django-rest :send POST request with 2 foreign key
我想 post 序列化器中的数据,有 2 个外键。
我有这些型号:
class Child(models.Model):
first_name = models.CharField(max_length=40)
description = models.CharField(max_length=40)
class Parent(models.Model):
name = models.CharField(max_length=20)
pet = models.ForeignKey(pet)
child = models.ForeignKey(Child, related_name='boys')
class Pet(models.Model):
kind = models.CharField(max_length=40)
------------------,
Class PetSerializer(ModelSerializer):
class Meta:
model = Pet
fields = ('kind',)
class ParentSerializer(ModelSerializer):
pet = PetSerializer(many=True):
class Meta:
model = Parent
fields = ('name', 'pet')
class ChildSerializer(ModelSerializer):
boys = ParentSerializer()
class Meta:
model = Child
fields = ('first_name', 'boys')
我的第一个问题:是否有可能得到如下输出:
{
"first_name": "Peter",
"boys": [
{
"name": "Bill",
"kind": "dog"
}
]
}
我的第二个 question:And 我正在尝试使用以下方法发送数据以创建新模型:
def create(self, validated_data):
clean_data = validated_data.pop('boys')
child = Child.objects.create(**validated_data)
for data in clean_data:
Parent.objects.create(child=child, **data)
return child
But I got this error: TypeError: Direct assignment to the reverse side of a related set is prohibited. Use boys.set() instead.
关于您的第一个问题,您可以在 ParentSerializer
class:
中使用 source parameter
class ParentSerializer(ModelSerializer):
kind = serializers.CharField(source='pet.kind'):
class Meta:
model = Parent
fields = ('name', 'kind')
我想 post 序列化器中的数据,有 2 个外键。
我有这些型号:
class Child(models.Model):
first_name = models.CharField(max_length=40)
description = models.CharField(max_length=40)
class Parent(models.Model):
name = models.CharField(max_length=20)
pet = models.ForeignKey(pet)
child = models.ForeignKey(Child, related_name='boys')
class Pet(models.Model):
kind = models.CharField(max_length=40)
------------------,
Class PetSerializer(ModelSerializer):
class Meta:
model = Pet
fields = ('kind',)
class ParentSerializer(ModelSerializer):
pet = PetSerializer(many=True):
class Meta:
model = Parent
fields = ('name', 'pet')
class ChildSerializer(ModelSerializer):
boys = ParentSerializer()
class Meta:
model = Child
fields = ('first_name', 'boys')
我的第一个问题:是否有可能得到如下输出:
{
"first_name": "Peter",
"boys": [
{
"name": "Bill",
"kind": "dog"
}
]
}
我的第二个 question:And 我正在尝试使用以下方法发送数据以创建新模型:
def create(self, validated_data):
clean_data = validated_data.pop('boys')
child = Child.objects.create(**validated_data)
for data in clean_data:
Parent.objects.create(child=child, **data)
return child
But I got this error: TypeError: Direct assignment to the reverse side of a related set is prohibited. Use boys.set() instead.
关于您的第一个问题,您可以在 ParentSerializer
class:
class ParentSerializer(ModelSerializer):
kind = serializers.CharField(source='pet.kind'):
class Meta:
model = Parent
fields = ('name', 'kind')