【发布时间】:2015-06-18 05:55:45
【问题描述】:
我是 Django 新手。我正在使用 Django REST Framework,我需要从序列化程序中获取以下格式的 json:
{
"result" : 200,
"categories" : [{
"id" : "V001",
"name": "Vehicles",
"description": "All types of motor and non-motor vehicles",
"icon": "http://images.maa.ae/static/icons/vehicles.png",
"subcategories": [{
"id" : "V00101",
"name": "Cars",
"description": "Motor Cars",
"subcategories": [{
"id" : "V0010101",
"name": "Passenger Cars",
"description": "All types of passenger cars"
}]
},
{
"id" : "V00102",
"name": "Bikes",
"description": "Bikes",
"subcategories": [{
"id" : "V0010201",
"name": "Motor Bikes",
"description": "All kinds of motor bikes"
},
{
"id" : "V0010202",
"name": "Sports Bikes",
"description": "All kinds of sports bikes"
}]
}]
}]
}
我的模型类是:
class Category(models.Model):
_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=128)
description = models.CharField(max_length=150,null=True, blank=True)
icon = models.ImageField(upload_to='icons',null=True, blank=True)
parent_id = models.ForeignKey('self', null=True, blank=True)
我的序列化程序类是:
class CategorySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Category
fields = ('_id', 'name', 'description', 'icon')
从上面的实现中,我可以得到 JSON 格式的 Category 对象数组。
但我不知道如何在我的序列化程序类中包含“子类别”。请帮助我获得类似于上述格式中显示的 json 的输出。
【问题讨论】:
-
您的问题到底是什么?如何从数据库中检索一些东西?如何创建 JSON?请edit您的问题更具体,只有一个问题。此外,请添加您正在使用的代码、您收到的任何错误或回溯的全文,以及对确切问题的详细描述。就目前而言,这个问题还很不清楚。
标签: django python-2.7 django-models