sorry if I ask very a simple question, I'm just starting to learn about WebDev and I have a question about django url and I used rest framework. I have http://localhost:8000/api/projectList/1 and I want to change id to the name in the url, for example http://localhost:8000/api/projectList/project This is the code:
model.py
class ProjectList(models.Model):
project = models.CharField(max_length=200)
project_name = models.CharField(max_length=200)
category = models.CharField(max_length=200)
academic = models.CharField(max_length=200)
view.py
class ProjectListSerializer(serializers.ModelSerializer):
class Meta :
model = ProjectList
fields = '__all__'
class ProjectListViewset(viewsets.ModelViewSet):
queryset = ProjectList.objects.all()
serializers_class = ProjectListSerializer
class ProjectListListView(generics.ListAPIView):
serializer_class = ProjectListSerializer
def get_queryset(self):
return ProjectList.objects.all()
class ProjectId(generics.RetrieveUpdateDestroyAPIView):
queryset = ProjectList.objects.all()
serializer_class = ProjectListSerializer
urls.py
urlpatterns = [
path("", include(router.urls)),
path("projectList/", ProjectListListView.as_view()),
path("projectList/<int:pk>", ProjectId.as_view()),
]
Thank you, sorry for my simple question and my bad English.
CodePudding user response:
In views and serializer define lookup_field = project, this will override the default id field.
Ps - make sure project is unique and primary key.
also change your url to accept string instead of int(id)
CodePudding user response:
Django Rest Framework ModelViewset doesn't require to declare separate view for detail. In ProjectListListView declare
lookup_field = 'project'
and delete
path("projectList/<int:pk>", ProjectId.as_view()),
from urlpatterns