0

I have a rest API app with users and books with this URL structure (without routers):

urlpatterns = [
    path('', UserList.as_view(), name="user-list"),
    path('<uuid:id>/', UserDetail.as_view(), name="user-detail"),
    path('<uuid:id>/books/', BookList.as_view(), name="book-list"),
    path('<uuid:id>/books/<int:book_id>/', BookDetail.as_view(), name="book-detail"),
]

Serializers:

class UserSerializer(serializers.HyperlinkedModelSerializer):
    books = serializers.HyperlinkedRelatedField(
        many = True,
        queryset = Book.objects.all(),
        view_name = "book-detail",
    )

And generic views:

class BookList(generics.ListAPIView):
    serializer_class = BookSerializer
    queryset = Book.objects.all()
    lookup_field = 'book_id'


class BookDetail(generics.RetrieveAPIView):
    serializer_class = BookSerializer
    queryset = Book.objects.all()
    lookup_field = 'book_id'

This doesn't work - I get the error:

Could not resolve URL for hyperlinked relationship using view name "book-detail"

I have tried changing the lookup_field and view-name, but I'm not even sure how to troubleshoot this issue.

I looked into drf-nested-routers, but I'm hoping to find a solution without switching to routers if at all possible.

Update:

I'm using book_id as my primary key in the model:

class Book(models.Model):
    book_id = models.AutoField(primary_key=True)
    owner = models.ForeignKey('users.ColossusUser', related_name="books", on_delete=models.CASCADE)
Toby
  • 12,743
  • 8
  • 43
  • 75
  • Change `book_id` to **`pk`** in urls.py and `BookDetail` view – JPG Sep 26 '18 at 18:26
  • Possible duplicate of [Custom Hyperlinked URL field for more than one lookup field in a serializer of DRF](https://stackoverflow.com/questions/32038643/custom-hyperlinked-url-field-for-more-than-one-lookup-field-in-a-serializer-of-d) – Brown Bear Sep 26 '18 at 18:29
  • I'm using `book_id` as my primary key - updated the code. Also, in searches the drf-nested-routers solutions didn't seem appropriate since I'm not using routers. – Toby Sep 26 '18 at 18:32
  • have you tried adding `lookup_field="book_id"` to the `HyperlinkedRelatedField` args? – RishiG Sep 26 '18 at 18:44
  • @RishiG I tried, it does not seem to change the error message. – Toby Sep 26 '18 at 18:54
  • https://stackoverflow.com/questions/20550598/django-rest-framework-could-not-resolve-url-for-hyperlinked-relationship-using – Amrit Sep 27 '18 at 09:30
  • I think the problem might be the missing `uuid` kwarg. What happens if you change the `book-detail` view path to `path('books//', BookDetail.as_view(), name="book-detail")` (i.e. without the `uuid`)? – slider Sep 27 '18 at 13:55
  • The idea was to try to achieve the nesting - but I've switched to routers, since that seems to be the generally recommended solution. Thanks. – Toby Sep 27 '18 at 14:01

0 Answers0