Efie
Efie

Reputation: 1690

How to get single field as result in django rest framework query?

So I'm setting up a REST API in Django and can't figure out how to return the result for a single field in a model with an http query. For example, let's say that our model User has the attributes 'id', 'username', and 'email'.

It's easy enough to return all related fields for that model instance, but how would I go about getting a single field from a query?

Something like myapp/api/user/1?username or myapp/api/user/1/username is what I'm looking for but I cannot find any good answers.

Upvotes: 0

Views: 4772

Answers (2)

Saji Xavier
Saji Xavier

Reputation: 2360

Another approach that works for all the fields in a Model,

class UserViewSet(viewsets.ViewSet):
    permission_classes = [IsAuthenticated]

    def field(self, request, pk, fname):
        user = User.objects.get(id=pk)
        data = getattr(user, fname)

        return Response({'result':data})

Modify the urls.py for routing to the view,

url(r'^user/(?P<pk>[0-9]+)/(?P<fname>\w+)/$', UserViewSet.as_view({'get': 'field',}), name='user-field'),

Url format will be,

/user/<user-id>/<field-name>/

Note: You can also add the error scenarios in the view for unknown fields etc (and send 4xx errors).

Upvotes: 1

Walucas
Walucas

Reputation: 2568

So do you want to filter over your model result, right? If so, looks like you need to create an APIView, get your model and then manipulate the field you want to display.

Something like this:

class UserField(APIView): 


    def get(self, request):
        path = str.split(str(request.path),'/')
        print(path)
        fieldname = path[4] #check your path on the print
        if fieldname= 'username':
            content={'username':User.objects.get(pk=path[3]).username}
                 content = {
                'fieldname': 'something',   
            }            

            return Response(content)

Upvotes: 1

Related Questions