mimic
mimic

Reputation: 1245

Django Rest Framework query with uid (username, userId)

I'm building an app with Django Rest framework.

Here is my Django model:

class Location(models.Model):
    uid = models.ForeignKey('auth.User', related_name='locations', unique=True, on_delete=models.CASCADE)
    area = models.IntegerField(choices=AREA, default=0)
    address = models.TextField(max_length=150)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('created_at',)
        verbose_name = 'Location'
        verbose_name_plural = 'Locations'

    def __str__(self):
        return self.area

My serializer:

class LocationSerializer(serializers.ModelSerializer):
    # owner = serializers.ReadOnlyField(source='owner.username')

    class Meta:
        model = Location
        fields = '__all__'

My view:

class LocationViewSet(viewsets.ModelViewSet):
    """
    This viewset automatically provides `list` and `detail` actions.
    """
    queryset = Location.objects.all()
    serializer_class = LocationSerializer
    permission_classes = (permissions.IsAuthenticated, permissions.IsAdminUser,)

My routes are registered using router.register

router = DefaultRouter()
router.register(r'locations', views.LocationViewSet)

When I query like this: localhost:8000/locations/<locationId> I get result of particular location matching location id. But I want to query with username/id like this: localhost:8000/locations/<username/uid> . How can I accomplish this?

P.S.: I'm new to Django.

Upvotes: 0

Views: 2326

Answers (1)

Deep 3015
Deep 3015

Reputation: 10075

We can override .get_queryset() to deal with URLs such as http://example.com/api/purchases?username=denvercoder9, and filter the queryset only if the username parameter is included in the URL:

class PurchaseList(generics.ListAPIView):
serializer_class = PurchaseSerializer

def get_queryset(self):
    """
    Optionally restricts the returned purchases to a given user,
    by filtering against a `username` query parameter in the URL.
    """
    queryset = Purchase.objects.all()
    username = self.request.query_params.get('username', None)
    if username is not None:
        queryset = queryset.filter(purchaser__username=username)
    return queryset

From Django REST framework Docs

Upvotes: 2

Related Questions