Django很多很多序列化器反转嵌套的json表示

时间:2018-05-31 14:10:14

标签: django django-rest-framework many-to-many

Django中的

具有多对多的关系,我使用selected_related来获取相关的表数据。但是,相关的表数据嵌套在每个记录中,我想反转关系,这可能没有自定义序列化器吗?

来自:

[
  {
    "id": 1,
    "item": " Sub item",
    "parent_items": {
        "id": 1,
        "description": "Parent Item Number 1",
 }
},
{
    "id": 2,
    "item": " Sub item 2",
    "parent_items": {
        "id": 2,
        "description": "Parent Item Number 2",
 }
]

反转父关系:

[
  {
    "parent_items": ""Parent Item Number 1",
    "id": 1,   
    "item": {
        "id": 1,
        "description": "Sub Item 1",
      }, 
     { 
     "item": {
        "id": 2,
        "description": "Sub Item 2 ",
  },

},
{  
    "parent_items": " Parent Item Number 2",
    "id": 2,

    "item": {
        "id": 1,
        "description": "SubItem Item 2",
  }  ............

]

这里是Serializer,Model和view。

模特:

class MainItem(models.Model):
   id = models.IntegerField(primary_key=True)
   description = models.CharField(max_length=50) 

class SubItem(models.Model):
  """Equates to parent items"""
  id = models.IntegerField(primary_key=True) 
  main_item = models.ForeignKey(MainItem, null=False)
  description = models.CharField(max_length=50) 


 class Main(models.Model):
  id = models.AutoField(primary_key=True)
  href = models.CharField(max_length=250)
  sub_items = models.ManyToManyField(SubItem)

The Serializer:

class SubItemSerializer(ModelSerializer):
    class Meta:
        model = SubItem
        fields = '__all__'
        depth = 1

观点:

class ItemsView(APIView):
      def get(self, request):

      items = SubItems.objects.select_related('main_item').all()
      issue_ser = SubItemSerializer(issues, many=True)

      return Response(issue_ser.data)

1 个答案:

答案 0 :(得分:2)

您应该重写代码,使其基于MainItem而不是SubItem

注意,您可以使用MainItem subitem_set属性获取所有相关的子项。 <modelname>_set是Django中多对一关系的默认反向相关名称。

所以尝试这样的事情:

class MainItemSerializer(ModelSerializer):
    class Meta:
        model = MainItem
        fields = ('id', 'description', 'subitem_set')
        depth = 1

class ItemsView(APIView):
      def get(self, request):
          items = MainItem.objects.prefetch_related('subitem_set').all()
          issue_ser = MainItemSerializer(issues, many=True)

          return Response(issue_ser.data)