返回一个模型的嵌套列表

时间:2018-07-15 12:40:34

标签: python django django-rest-framework

我有一个查找表,其中包含课程类别和子类别,分别为:

{
        "id": 138,
        "lookup": "CRS_CTGRY",
        "attr1": "Arts and Humanities",
        "attr2": "الفنون والعلوم الإنسانية",
        "attr3": null,
        "attr4": null,
        "attr5": null,
        "editable": 1
    },

{
        "id": 155,
        "lookup": "CRS_SB_CTGRY",
        "attr1": "Photography",
        "attr2": "النصوير",
        "attr3": "138",
        "attr4": null,
        "attr5": null,
        "editable": 1
    },

它们之间的关系是attr3 = id_of_the_category && attr1 = CRS_SB_CTGRY

我想将它们合并到一个列表中,例如:

{"id":138,"
"lookup":"CRS_CTRGY",
"name":"Arts and Humanities",
"subcategories":{"id": 154,
                 "lookup": "CRS_SB_CTGRY",
                  "attr1": "Music",
                  "attr2": "الموسيقي",
                  "attr3": "138",
                  "attr4": null,
                   "attr5": null,
                    "editable": 1
}}

这是我的模型。py:

class Lookups(models.Model):
lookup = models.CharField(max_length=45)
attr1 = models.CharField(max_length=100)
attr2 = models.CharField(max_length=100, blank=True, null=True)
attr3 = models.CharField(max_length=100, blank=True, null=True)
attr4 = models.CharField(max_length=100, blank=True, null=True)
attr5 = models.CharField(max_length=100, blank=True, null=True)
editable = models.IntegerField(blank=True, null=True)

class Meta:
    managed = True
    db_table = 'lookups'
    unique_together = (('lookup', 'attr1', 'attr2', 'attr3', 'attr4', 'attr5'),)

我该怎么办?在哪里放置代码?在序列化程序类中?

2 个答案:

答案 0 :(得分:0)

如果这是两个模型,则一个内部序列化。 http://www.django-rest-framework.org/api-guide/relations/#nested-relationships

答案 1 :(得分:0)

您需要为您的子类别实现序列化程序:

 class SubcategorySerializer(serializers.ModelSerializer):
      class Meta:
          model = Lookups
          fields = ( 'id', 'lookup', 'attr1', 'attr2', 'attr3',)

并在选择所有相关子类别时在类别序列化程序中使用它:

 class CategorySerialier(serializers.ModelSerializer): 
      subcategories =  serializers.SerializerMethodField(read_only=True)

      class Meta:
          model = Lookups
          fields = ( 'id', 'lookup', 'subcagories')

      def get_subcategories(self, obj):
          subs = Lookups.objects.filter(attr3=obj.id)
          return SubcategorySerializer(subs,many=True).data