我想使用URL作为http://127.0.0.1:8000/db/User/email(即使用电子邮件作为查询)而不是http://127.0.0.1:8000/db/User/1/获得模型实例。如何解决这个问题。
型号:
class Employee(models.Model):
firstname = models.CharField(max_length=100)
email = models.CharField(max_length=100)
serializers.py
class EmployeeSerializers(serializers.ModelSerializer):
field = NestedSerializers()
class Meta:
model = Employee
fields = '__all__'
def create(self, validated_data):
#overwrite this method for writable nested serializers.
view.py:
class UserView(viewsets.ModelViewSet):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializers
urls.py:
router = routers.DefaultRouter()
router.register('User', views.UserView)
urlpatterns = [
path('', views.index, name='index'),
path('/', include(router.urls))
]
可以使用ModelViewSet吗?
答案 0 :(得分:0)
我看到您正在使用DRF视图集。如果您只想使用电子邮件而不是ID,则可以像这样重写视图集的检索功能:
from django.shortcuts import get_object_or_404
class UserView(viewsets.ModelViewSet):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializers
def retrieve(self, request):
employee = get_object_or_404(
self.queryset,
email=self.kwargs['email']
)
serializer = self.serializer_class(employee)
return Response(serializer.data)
网址
router = routers.DefaultRouter()
router.register('^User/(?P<email>.+)/$', views.UserView)
urlpatterns = [
path('', views.index, name='index'),
path('/', include(router.urls))
]
检索是viewset类中已经提供的功能