1

I'm looking for the place in Django REST Framework to hook in when wanting to format the result of a query in a specific way.

That is, I want to take all the rows returned by a query and create a very specific type of JSON response with some meta data and a different (nested) structure.

It seems that serializers take care of one row at a time. Are custom views the right place for this?

dalgard
  • 3,614
  • 2
  • 22
  • 28

3 Answers3

3

I hope this helps... (Django 1.8)

Model:

class Users(AbstractBaseUser):
    email = models.EmailField(unique=True)
    username = models.CharField(max_length=100, blank=True)
    first_name = models.CharField(max_length=100, blank=True)
    last_name = models.CharField(max_length=100, blank=True)
    company = models.ForeignKey(Company)

Serializer:

    class UserListSerializer(serializers.ModelSerializer):
        company_name = serializers.SerializerMethodField()
        def get_company_name(self, obj):
            return obj.company.name

        class Meta:
            model = Users
            fields = ('id', 'email', 'username', 'first_name', 'last_name',
                     'company_name','company')

With SerializerMethodField you can add any custom value for your record. You can modify your serializer with this method.

Umut Gunebakan
  • 391
  • 3
  • 14
2

One way to do this is by overriding the to_representation method in serializers.ListSerializer.

class CustomListSerializer(serializers.ListSerializer):

    def to_representation(self, instances):
        data = []
        for instance in instances:
            field1 = instance.field1
            field2 = instance.field2
            data.append({'field1':field1,'field2':field2})
        return data

class YourSerializer(serializers.ModelSerializer):

    class Meta:
        model = YourModel
        list_serializer_class = CustomListSerializer

to_representation method in serializers.ListSerializer converts List of object instances to List of dicts of primitive datatypes.

I have just shown you an example of what can be done. You can modify the to_representation to your requirement. Just make sure your dictionaries are inside a list.

Anush Devendra
  • 5,285
  • 1
  • 32
  • 24
1

As far as I know you don't need any hook, DRF has default support for nested results, you need just to use the right serializer class based on the relation between the models and how you want it to be displayed.

class ModelASerializer(serializers.ModelSerilizer):
      modelb = ModelBSerializer(many=True) # case many to many realtionship

oder

      modelb = ModelBSerializer(read_only=True) # case foreign key

so based on your needs you can format your response using serializers, there is also serializers.DictField, serializers.ListField for field serialization.

Check Model Serializer, Field Serializer

Dhia
  • 10,119
  • 11
  • 58
  • 69