我对 Python-Django 和 web 开发非常陌生,我被困在使用 POST 创建新资源的特殊问题上。
我正在为 REST API 使用 Django REST 框架,并且我正在尝试创建一个新资源。该模型具有外键关系,我希望一次性创建相关资源。我发布了一个示例模型、序列化程序和视图,以便我清楚我的问题。
** 我的模型有两个具有多对一关系的类。
class Carmodel(models.Model):
modelkey = models.BigIntegerField(primary_key=True)
makerkey = models.ForeignKey('Carmaker', db_column='makerkey', related_name='models')
modelname = models.CharField(max_length=1024)
class Meta:
db_table = 'carmodel'
class Carmaker(models.Model):
makerkey = models.BigIntegerField(primary_key=True)
makername = models.CharField(max_length=1024)
class Meta:
db_table = 'carmaker'
** 我有如下的序列化程序类
class CarmodelSerializer(serializers.ModelSerializer):
class Meta:
model = Carmodel
fields = ('modelkey','makerkey','modelname')
class CarmakerSerializer(serializers.ModelSerializer):
models = CarmodelSerializer(many=True)
class Meta:
model = Carmaker
fields = ('makerkey','makername','models')
** 我试图创建资源的视图看起来像
@api_view(['POST'])
def carmaker(request, makerkey, format=None):
if request.method == 'POST':
serializer = CarmakerSerializer(data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
** 我的输入看起来像这样,我想创建 Carmaker 资源以及嵌套的 Carmodel。
{
"makerkey": 1,
"makername": "lamborghini",
"models": [
{
"modelkey": 11,
"makerkey": 1,
"modelname": "reventon"
},
{
"modelkey": 12,
"makerkey": 1,
"modelname": "aventador"
}
]
}
** 我收到的回复为
{
"models": [
{
"makerkey": [
"Invalid pk '1' - object does not exist."
]
},
{
"makerkey": [
"Invalid pk '1' - object does not exist."
]
}
]
}
有没有办法在单个 POST 请求中创建这种资源?提前致谢