我是django和drf的新手,我试图设置一个简单的api以返回“个性模型”的“列表”和“详细信息”视图。我希望这些网址使用slug字段而不是默认的pk。 / p>
使用默认的“ pk”字段解析网址时,效果很好,但是当我尝试通过lookup_field使用slug字段时, 我收到以下错误:
[ERROR]'在/ personality /中配置不正确 无法使用视图名称>“个性详细信息”来解析超链接关系的URL。您可能无法将相关模型包括在您的API中,或者在此字段上的
lookup_field
属性配置不正确。'
models.py:
class Personality(models.Model):
personality_name = models.CharField(
"Influential Person", unique=True, max_length=100
)
slug = models.SlugField(blank=True, unique=True, max_length=100)
info = models.TextField("Information")
trivia = models.TextField("Trivia")
def __str__(self):
return self.personality_name
def save(self, *args, **kwargs):
if not self.id:
self.slug = slugify(self.personality_name)
super(Personality, self).save(*args, **kwargs)
views.py
class PersonalityViewSet(viewsets.ModelViewSet):
queryset = Personality.objects.all().order_by("id")
serializer_class = PersonalitySerializer
lookup_field = "slug"
serializers.py:
class PersonalitySerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(
view_name="personality-detail", lookup_field="slug"
)
class Meta:
model = Personality
fields = ("pk", "personality_name", "url", "slug", "info", "trivia")
read_only_fields = ("pk", "slug")
# lookup_field = "slug"
# extra_kwargs = {"url": {"lookup_field": "slug"}}
quotes / urls.py
router = routers.DefaultRouter()
router.register(r"personality", views.PersonalityViewSet)
urlpatterns = [path("", include(router.urls))]
urls.py
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("quotes.urls")),
path("api-auth", include("rest_framework.urls", namespace="rest_framework")),
]