我有一个非常简单的问题,无法解决。我有以下型号
class Parent(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=64)
class Child(models.Model):
boardid = models.ForeignKey(Parent,on_delete=models.CASCADE,related_name="child")
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=128)
序列化器
class ParentSerializer (serializers.ModelSerializer):
class Meta:
model = Parent
fields = ('__all__')
class ChildSerializer (serializers.ModelSerializer):
class Meta:
model = Child
fields = ('id','title')
和针对孩子的简单createAPIview
class ChildCreateView(CreateAPIView):
queryset= Child.objects.all()
serializer_class = ChildSerializer
当我调用此网址时 / api / parent / 1 / child / create 我想用ID 1预先填充外键ID,并用我将在正文中提供的其余信息创建子对象。这怎么可能实现
答案 0 :(得分:1)
首先将 boardid
字段添加到 ChildSerializer
,
class ParentSerializer(serializers.ModelSerializer):
class Meta:
model = Parent
fields = '__all__' # no need of "()"
class ChildSerializer(serializers.ModelSerializer):
class Meta:
model = Child
fields = ('id', 'title', 'boardid')
然后,使用下面的json有效负载创建实例。
{
"title":"child title",
"boardid":123,
... other data
}