我正在使用Django和Restframework创建一个API。
数据是我希望API以这样的方式输出;MasterResource";models是Parent;章节";与匹配的";MasterResource";然后所有相关的";项目";与";章节";。
我的模型目前看起来是这样的:
class MasterResource(models.Model):
route_name = models.CharField(max_length=100)
resourceId = models.CharField(primary_key=True, max_length=100)
class ResourceSection(models.Model):
resourceId = models.ForeignKey(MasterResource, on_delete=models.CASCADE, default=1)
resource_name = models.CharField(max_length=100)
sectionId = models.CharField(primary_key=True, max_length=100)
class SectionItem(models.Model):
sectionId = models.ForeignKey(ResourceSection, on_delete=models.CASCADE,default=1)
item_title = models.CharField(max_length=100)
image = models.ImageField(blank=True)
link = models.URLField()
我的观点是这样的:
@csrf_exempt
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create_resource(request):
if request.method == 'POST':
try:
resourceId = request.POST.get("resourceId")
route_name = request.POST.get("route_name")
result = {}
result['resourceDetails'] = json.loads(serializers.serialize('json',[MasterResource.objects.get(resourceId=resourceId)]))
result['sectionDetails'] = json.loads(serializers.serialize('json',ResourceSection.objects.filter(resourceId__resourceId = resourceId)))
result['itemDetails'] = json.loads(serializers.serialize('json',SectionItem.objects.filter(sectionId__sectionId=sectionId)))
return JsonResponse(result, safe=False)
except Exception as e:
return HttpResponseServerError(e)
我已经实现了接收";MasterResource";及其相关的";截面";,但是相关的";项目";无输出
电流输出
{
"resourceDetails": [
{
"model": "userdata.masterresource",
"pk": "1234",
"fields": {
"route_name": "Testing test"
}
}
],
"sectionDetails": [
{
"model": "userdata.resourcesection",
"pk": "112233",
"fields": {
"resourceId": 1234,
"resource_name": "Test section"
}
},
{
"model": "userdata.resourcesection",
"pk": "223344",
"fields": {
"resourceId": 1234,
"resource_name": "Test section2"
}
}
],
"itemDetails": []
}
所需输出如下:
{
"resourceDetails": [
{
"model": "userdata.masterresource",
"pk": "1234",
"fields": {
"route_name": "Testing test"
}
}
],
"sectionDetails": [
{
"model": "userdata.resourcesection",
"pk": "112233",
"fields": {
"resourceId": 1234,
"resource_name": "Test section"
}
},
{
"model": "userdata.resourcesection",
"pk": "223344",
"fields": {
"resourceId": 1234,
"resource_name": "Test section2"
}
}
],
"itemDetails": [
{
"model" : "userdata.sectionitem",
"pk": "1",
"fields" : {
"sectionId" : 112233
"item_title" : "test"
"image" : "some_image"
"link" : "www.google.com"
}
}
]
}
我找到了上述问题的解决方案。
由于我们需要一个部分的所有项的输出,因此我们需要提供一个键或id,我们需要这些项。
这意味着除了resourceId = request.POST.get("resourceId")
之外,还必须有另一个POST数据来说明需要哪个Item数据,即刚好低于resourceId的sectionId = request.POST.get("sectionId")
。
因此串行化数据将变为result['itemDetails'] = json.loads(serializers.serialize('json',SectionItem.objects.filter(sectionId__sectionId=sectionId)))