[Django]-Django rest framework: convert queryset to json response

16👍

You need to write a serializer to display the data in the desired format. Read the excellent tutorial to guide you though it properly. But if you want a quick hacky answer, then do something like this:

serializer = AppointmentSerializer(Appointment.objects.all(), many=True)
return Response(serializer.data)

Where the serializer looks something like this:

class AppointmentSerializer(serializers.ModelSerializer):
    customer = CustomerSerializer(required=False, allow_null=True)

    class Meta:
        model = Appointment
        fields = ('id', 'customer', 'status', 'etc...')
        related_object = 'customer'

class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = ('id', 'first_name', 'etc...')

Edit: updated to include example of a related object

Leave a comment