我遇到错误
无法使用视图名称解析超链接关系的URL “分类详细信息”。您可能未能将相关模型包括在 您的API,或在
lookup_field
属性上配置错误 此字段。
这是MWE:
from django.contrib import admin
from django.urls import include, path
from rest_framework import routers
from testproj import views
router = routers.DefaultRouter()
router.register(r'taxonomy', views.TaxonomyViewSet)
router.register(r'taxonomy-term', views.TaxonomyTermViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include(router.urls))
]
from django.db import models
class Taxonomy(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
slug = models.SlugField()
def __str__(self):
return self.name
class Meta:
verbose_name = "Taxonomy"
verbose_name_plural = "Taxonomies"
class TaxonomyTerm(models.Model):
taxonomy = models.ForeignKey(
"Taxonomy",
on_delete=models.CASCADE,
related_name="terms",
related_query_name="term"
)
parent = models.ForeignKey(
"self",
on_delete=models.CASCADE,
related_name="children",
related_query_name="child",
blank=True,
null=True
)
name = models.CharField(max_length=255,)
description = models.TextField()
slug = models.SlugField(unique=True)
def __str__(self):
return self.name
class Meta:
verbose_name = "Term"
verbose_name_plural = "Terms"
from testproj.models import TaxonomyTerm, Taxonomy
from rest_framework import serializers
class TaxonomySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Taxonomy
fields = ('name', 'description', 'slug')
lookup_field = 'slug'
extra_kwargs = {
'url': {'lookup_field': 'slug'}
}
class TaxonomyTermSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = TaxonomyTerm
fields = ('taxonomy', 'parent', 'name', 'description', 'slug')
lookup_field = 'slug'
extra_kwargs = {
'url': {'lookup_field': 'slug'}
}
from rest_framework import viewsets
from testproj.models import Taxonomy, TaxonomyTerm
from testproj.serializers import TaxonomySerializer, TaxonomyTermSerializer
class TaxonomyViewSet(viewsets.ModelViewSet):
queryset = Taxonomy.objects.all().order_by('name')
serializer_class = TaxonomySerializer
lookup_field = 'slug'
class TaxonomyTermViewSet(viewsets.ModelViewSet):
queryset = TaxonomyTerm.objects.all().order_by('name')
serializer_class = TaxonomyTermSerializer
lookup_field = 'slug'
到底是怎么回事?我浏览了许多类似的问题,但看不到自己犯了任何常见的错误。
答案 0 :(得分:1)
TaxonomyTermSerializer
没有为lookup_field
超链接提供parent
,也没有为taxonomy
提供超链接。
它应与:
class TaxonomyTermSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = TaxonomyTerm
fields = ('taxonomy', 'parent', 'name', 'description', 'slug')
lookup_field = 'slug'
extra_kwargs = {
'url': {'lookup_field': 'slug'},
'taxonomy': {'lookup_field': 'slug'},
'parent': {'lookup_field': 'slug'},
}