2

I am using drf-nested-routers to nest my resources and everything is working well. I would like, however, to use something other than the pk to refer to a parent object.

What I currently have is:

api/movies/4/scenes - generates a list of scenes from movie with pk=4.

What I would like is:

api/movies/ghost-busters/scenes - where the identifier is movie.title instead of movie.pk

Any suggestions?

Thanks

purplefloyd
  • 155
  • 1
  • 12
  • 1
    set look_up_field for your class – Ykh Mar 24 '17 at 01:39
  • There is a good answer [here](http://stackoverflow.com/questions/32201257/django-rest-framework-access-item-detail-by-slug-instead-of-id). In a nutshell: create a slug field in your model, add a lookup_field to your ModelViewSet and thats it. – Dan Mar 24 '17 at 03:47

1 Answers1

2

you can use slug for the url you want to make "api/movies/ghost-busters/scenes"

at first you have to make model with slugField eg.

class Blog(models.Model):
    qoute = models.CharField(max_length=30)
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.qoute)
        super(Blog, self).save(*args, **kwargs)

during the saving model it will create a slug by "qoute" and save to the column "slug"

make your urls.py entry

url(r'^api/movies/(?P<slug>[\w-]+)/scenes/$', 'myapp.views.blog_detail', name='blog_detail'),

then for the drf you have set lookup_field in the serializer and view also. N.B: you can user ModelSerializer or Serializer or HyperlinkSerialzer as you wish..

class BlogSerializer(serializers.ModelSerializer):

    class Meta:
        model = Blog
        fields = ('quote', 'slug',)
        lookup_field = 'slug'

and the views..

class blog_detail(generics.RetrieveUpdateDestroyAPIView):

    queryset = Blog.objects.all()
    serializer_class = BlogSerializer
    lookup_field = 'slug'