【问题标题】:DRF: viewsets lookup_field ImproperlyConfiguredDRF:视图集lookup_field 配置不当
【发布时间】:2022-02-06 21:26:33
【问题描述】:

我正在将我的 DRF 从泛型迁移到视图集,但收到此错误:

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

这是我的 urls.py

from app.api import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'monuments', views.MonumentsViewSet)

urlpatterns = router.urls

这是我的观点

from app.api import serializers
from rest_framework import viewsets


class MonumentsViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.MonumentSerializer
    queryset = serializer_class.Meta.model.objects.all()
    lookup_field = 'id'

最后是我的序列化器

from app.api import models
from rest_framework import serializers


class MonumentSerializer(serializers.HyperlinkedModelSerializer):
    images = serializers.StringRelatedField(many=True)

    class Meta:
        model = models.Monument
        fields = '__all__'

【问题讨论】:

  • 为什么images字段使用monument的链接?
  • @BearBrown 是一个错误,但是如果我删除这个参数,它会给我这个错误assert self.view_name is not None, 'The view_name argument is required.'
  • 你能展示你的模型吗?

标签: python django django-rest-framework django-rest-viewsets


【解决方案1】:

删除lookup_field = 'id'。我不知道为什么会这样,但是当我复制你的代码时它就起作用了。

P.S 你的错误说,你错误地配置了 'lookup_field'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2017-10-29
    • 2021-12-12
    • 1970-01-01
    相关资源
    最近更新 更多