我正在尝试将一个查询集解析为一个JSON对象,以便每个键都是模型的主键,每个值都是一个包含所有其他字段的JSON对象。
myjson = {
apple: { color: "r", calories: 10},
banana: { color: "w", calories: 50}
}
以下是收集数据的模型和Django视图(基于此blog post):
class Fruit(models.Model):
fruit_id = models.CharField(primary_key=True)
color = models.CharField(max_length=50)
calories = models.IntegerField()
def get_FruitsTableDjango(request):
fruits_table = Fruit.objects.all().values()
fruits_table_list = list(fruits_table ) # important: convert the QuerySet to a list object
return JsonResponse(fruits_table_list , safe=False)
但是在客户端(通过AJAX),这将返回对象数组:
mydata = [
0: { fruit_id: "apple", color: "r", calories: 10},
1: { fruit_id: "banana", color: "w", calories: 50}
]
我还here发现了如何按预期对这个数组进行返工:
//Restructure JSON by fruit_id name
fruits= {},
mydata.forEach(function (a) {
var temp = {};
Object.keys(a).forEach(function (k) {
if (k === 'fruit_id') {
fruits[a[k]] = temp; //gets fruit_id
return;
}
temp[k] = a[k]; //fill the temp variable with elements
});
});
mydata=fruits; //overwrite initial array with nicely-rearranged-by-fruitId object
我基本上有两个问题:
答案 0 :(得分:0)
在DRF中,
假设我有如下的model.py
from django.db import models
class OrganisationalUnitGrouper(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
@property
def unit(self):
return self.organisationalunit_set.all()
class OrganisationalUnit(models.Model):
unit_id = models.CharField(max_length=255)
name = models.CharField(max_length=255)
display = models.CharField(max_length=255)
description = models.CharField(max_length=255)
path = models.CharField(max_length=255)
ou_group = models.ForeignKey(OrganisationalUnitGrouper, on_delete=models.PROTECT)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "OU Unit"
序列化器,您可以定义
from rest_framework import serializers
from .models import OrganisationalUnitGrouper, OrganisationalUnit
class OUSerializer(serializers.ModelSerializer):
# id = serializers.IntegerField(required=False)
class Meta:
model = OrganisationalUnit
fields = ("unit_id", "name", "display", "description", "path")
class OUGroupSerializer(serializers.ModelSerializer):
unit = OUSerializer(many=True)
class Meta:
model = OrganisationalUnitGrouper
fields = ("name", "unit")
视图集可能是
from rest_framework import viewsets
from .serializers import OUSerializer, OUGroupSerializer
from .models import OrganisationalUnitGrouper, OrganisationalUnit
class OUGroupViewSet(viewsets.ModelViewSet):
queryset = OrganisationalUnitGrouper.objects.all()
serializer_class = OUGroupSerializer
class OUViewSet(viewsets.ModelViewSet):
queryset = OrganisationalUnit.objects.all()
serializer_class = OUSerializer
这将为您提供嵌套的API。