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)