2

I am using the Django REST Framework toolkit with Django 1.11 and I am trying to filter the results against the url. Here is my setup:

models.py:

from django.db import models

class Package(models.Model):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
    return self.name

serializers.py:

from rest_framework import serializers
from .models import Package

class PackageSerializer(serializers.ModelSerializer):
      class Meta:
            model = Package
            fields = ('name',)

views.py:

from rest_framework import viewsets
from .models import Package
from .serializers import PackageSerializer

class PackageViewSet(viewsets.ReadOnlyModelViewSet):
     serializer_class = PackageSerializer
     queryset = Package.objects.all()

urls.py

from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'package', views.PackageViewSet)

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/v1/', include(router.urls)),
]

Currently when I use this I can filter the results by the id field:

http://127.0.0.1:8000/api/v1/package/1/

I am hoping to filter the results by the name field of my package model instead by using this:

http://127.0.0.1:8000/api/v1/package/basic/

How would I be able to accomplish this?

2 Answers 2

3

Set the lookup_field attribute in the viewset, see the documentation.

class PackageViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = PackageSerializer
    queryset = Package.objects.all()
    lookup_field = 'name'
Sign up to request clarification or add additional context in comments.

1 Comment

And I thought Google was fast... thank you for the quick reply and the link to the documentation.
0

Use filter_fields in views.

filter_fields = ('name',)

lookup field is used to set lookup by default it would be model pk

if you wish to make your URL,

my_url/filter_field/

set lookup_field = "name"

if you want search from URL like ,

my_url/?name=something

you need to set filter_fields in views.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.