1

I am trying to construct a class based Django REST API that takes in data from the POST request and outputs the relevent data.

I have a list of buildings in the DB

State         Building
California    Golden Gate Bridge
New York      Empire State
California    TransAmerica
New York      Brooklyn Bridge

User will supply the state through a POST Request (i.e. California), the API should return the appropriate building (i.e. Golden Gate Bridge, TransAmerica)

I guess I'm just having a hard time understand how the class is taking in the request.data ['state_id']. Should I use APIView? So many questions!

So far I have this in my view.py

class BuildingViewSet(viewsets.ModelViewSet):
    queryset = BuildingRule.objects.values('building_name').distinct()
    serializer_class = BuildingSerializer

    def post(self, request, *args, **kwargs):
        queryset = BuildingRule.objects.filter(state_name=request.data['state_id'])
        return Response(queryset.values_list('building_name', flat=True))

This is in my serializer.py

class BuildingSerializer(serializers.ModelSerializer):
    class Meta:
        model = BuildingRule
        fields = ('building_name',)

This is my url.py:

 router.register(r'buildings', views.BuildingsViewSet, base_name='Building')
H C
  • 1,138
  • 4
  • 21
  • 39
  • override create method in your viewset.... follow this link https://stackoverflow.com/questions/40999386/custom-function-which-performs-create-and-update-on-drf-modelviewset – Amrit Sep 28 '17 at 04:34
  • 1
    Overriding the create method in the viewset is not the right way to do it. With DRF and a Serializer just use the `required` attribute on a Field like I described in my answer. – Johannes Reichard Sep 29 '17 at 10:58

1 Answers1

1

You should checkout the Django rest framework Serializer: http://www.django-rest-framework.org/tutorial/1-serialization/ to get a basic understanding of drf and how to use it.

You will find the answer to your question in 'Creating a Serializer class'.