python - DRF 在覆盖 get_queryset 时抛出 django.core.exceptions.ImproperlyConfigured

标签 python django django-rest-framework

Django Rest 框架抛出:

django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "customuser-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.



当我尝试 覆盖 get_queryset .
我的用户序列化程序:

class UserSerializer(serializers.HyperlinkedModelSerializer):
    """
    Represent User Serializer class.
    """
    teacher_account = TeacherSerializer(required=False)
    student_account = StudentSerializer(required=False)

    account_type = serializers.IntegerField(required=True)

    class Meta:
        model = CustomUser
        fields = ['url', 'username', "password", 'email', 'first_name', 'last_name', "account_type", 'teacher_account', 'student_account']

        email_validator = UniqueValidator(queryset=CustomUser.objects.all(), message="A user with that email already exists.")

        extra_kwargs = {
            "password": {"write_only": True},
            "email": {"required": True, "validators": [email_validator]}
        }

    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.select_related('teacher_account', 'student_account')
        return queryset


用户/模型.py:
class StudentAccount(models.Model):
    """
    Represent student's account model.

    """
    classes = models.ManyToManyField('classroom.Class', related_name="students")


class TeacherAccount(models.Model):
    """
    Represent teacher's account.

    use get_subject_name from {root}/utils.py for get name of the subject.
    """

    subject_id = models.PositiveSmallIntegerField("Предмет", choices=SUBJECTS_CHOICES, blank=False, default=0)


class CustomUser(AbstractUser):
    """
    Represent Custom user model, inherited from AbstractUser

    account_type = 0(teacher) or 1(student)
    """
    student_account = models.OneToOneField(StudentAccount, on_delete=models.CASCADE, blank=True, null=True, related_name="user")
    teacher_account = models.OneToOneField(TeacherAccount, on_delete=models.CASCADE, blank=True, null=True, related_name="user")

    account_type = models.PositiveSmallIntegerField(default=1)

    first_name = models.CharField("-", max_length=30, blank=False)
    last_name = models.CharField("-", max_length=150, blank=False)


我的意见.py:
class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """

    permission_classes = (permissions.AllowAny,)
    # queryset = CustomUser.objects.all()
    # queryset_raw = CustomUser.objects.all()
    # queryset = UserSerializer.setup_eager_loading(queryset_raw)
    model = CustomUser
    serializer_class = UserSerializer

    def get_queryset(self):
        queryset = CustomUser.objects.all()
        # queryset = self.get_serializer_class().setup_eager_loading(queryset)
        return queryset

我的 urls.py:
from django.urls import path, include

from rest_framework import routers
from knox import views as knox_views

from .views import UserViewSet, ClassViewSet, LoginView, LessonViewSet

router = routers.DefaultRouter()
router.register('users', UserViewSet, basename="CustomUser")
router.register('classes', ClassViewSet)
router.register('lessons', LessonViewSet)


urlpatterns = [
    path('login/', LoginView.as_view(), name='knox-login'),
    path('logout/', knox_views.LogoutView.as_view(), name="knox_logout"),
    path('logoutall/', knox_views.LogoutAllView.as_view(), name="knox_logoutall"),
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]


我意识到,如果我将覆盖显示用户模型详细信息的页面的 url,则可以修复它。但我认为有更多正确的答案。
path('api/users/<int:pk>/', UserViewSet.as_view({"get": "retrieve", "put": "update", "delete": "destroy"}), name="customuser-detail")

最佳答案

根据 documentation , basename您在注册时提供 ViewSet到您的路由器将用于生成 URL 模式。您提供了 basename=CustomUser , 有大写。

正如错误指出的那样(另请参阅 documentation,了解如何确定超链接 View 和构造默认名称)您的基名应该是小写的。

如果您想保持大写,请参阅前面的文档链接以实现自定义 view_name='CustomUser-detail'HyperlinkedModelSerializer .

关于python - DRF 在覆盖 get_queryset 时抛出 django.core.exceptions.ImproperlyConfigured,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60211884/

相关文章:

Python argparse 示例?

python - Django 休息框架 : How to initialise & use custom exception handler?

javascript - 如何在 django 关闭浏览器时终止 session

django - 模板中的多对多项目 : check if any are not empty or none

django - 'DjangoFormMutationOptions' 对象没有属性 'model'

python - 在 Django Rest Framework 中找不到资源时返回自定义 404 错误

python - 我希望我的 django rest 框架序列化程序接受输入但不添加到模型

python - python 中奇怪的列表行为

python 将字符串添加到数组中每个元素的开头

python - 将 json 数据转换为 dataframe 或 csv