return a nested list of one model

2019-08-22 18:25发布

问题:

I have a lookups table that contains course categories and subcategories separate:

{
        "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
    },

The relation between them is that attr3 = id_of_the_category && attr1 = CRS_SB_CTGRY

I want to merge them together in one list like:

{"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
}}

This is my models.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'),)

How can i do it? and where to put the code? in the serializers class?

回答1:

You need to implement serializer for your subcategory:

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

And use it in your Category Serializer when you select all related subcategories:

 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


回答2:

If these are two models, and one serialize inside the other. http://www.django-rest-framework.org/api-guide/relations/#nested-relationships