Reputation: 337
i have these serializer on Django
class CarManagerSerializer(serializers.ModelSerializer):
class Meta:
model = Manager
fields = '__all__'
and this view class
class CarManagerViewSet(APIView):
allowed_methods = ('GET',)
def get(self, request, manager_id = None):
if manager_id is None:
managers = Manager.objects.all().order_by('-name')
serializer = CarManagerSerializer(managers , many=True)
serializer_data = serializer.data
return Response(serializer_data, status=status.HTTP_200_OK)
else:
managers = Manager.objects.get(id = manager_id).select_related('cars')
serializer = CarManagerSerializer(managers , many=True)
serializer_data = serializer.data
return Response(serializer_data, status=status.HTTP_200_OK)
im trying to get the manager by its manager id
http://127.0.0.1:8000/carmanagers/3
but the manager_id wont get passed to the view, i keep getting 'None' where did i miss ? below is the url
urlpatterns = [
url(
r'carmanagers/(?P<manager_id>[0-9]+)/$',
CarManagerViewSet.as_view(),
name='car-managers'
),
url(
r'carmanagers',
CarManagerViewSet.as_view(),
name='car-managers'
),
]
Upvotes: 1
Views: 81
Reputation: 477883
The reason is that there is no slash at the end of your path, so the first path will not match immediately, but the second path will match, because of lack of anchors. This means that your r'carmanagers'
path will match each time the path contains carmanagers
. You should add a start and end anchor:
urlpatterns = [
url(
r'carmanagers/(?P<manager_id>[0-9]+)/$',
CarManagerViewSet.as_view(),
name='car-managers'
),
url(
# ↓ anchors ↓
r'^carmanagers/$',
CarManagerViewSet.as_view(),
name='car-managers'
),
]
Note: As of django-3.1,
url(…)
[Django-doc] is deprecated in favor ofre_path(…)
[Django-doc]. Furthermore a new syntax for paths has been introduced with path converters: you usepath(…)
[Django-doc] for that.
Upvotes: 1