【发布时间】:2020-06-07 22:26:29
【问题描述】:
我知道这里有很多类似的问题,但我尝试了大多数答案,但到目前为止都没有奏效......
我得到的错误是:
ImproperlyConfigured at /matches/1/
Could not resolve URL for hyperlinked relationship using view name "matchteam-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
但是,matchteam-detail 在我的 urlpatterns 中:
<URLPattern '^matchteams/(?P<pk>[^/.]+)/$' [name='matchteam-detail']>, <URLPattern '^matchteams/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$' [name='matchteam-detail']>,
当访问 API 上的“匹配”对象时,此错误发生在与 Django REST 框架上的“直通”模型的多对多关系上:
models.py
class MatchTeam(models.Model):
team = models.ForeignKey("teams.Team", on_delete=models.CASCADE)
match = models.ForeignKey("matches.Match", on_delete=models.CASCADE)
score = models.PositiveSmallIntegerField(default=0)
class Match(models.Model):
teams = models.ManyToManyField("teams.Team", through='matches.MatchTeam')
class Team(models.Model):
matches = models.ManyToManyField("matches.Match", through='matches.MatchTeam')
serializers.py
class MatchTeamSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MatchTeam
fields = ['id', 'team', 'match', 'score']
class MatchSerializer(serializers.HyperlinkedModelSerializer):
teams = serializers.HyperlinkedRelatedField(
read_only=True,
view_name='matchteam-detail',
)
class Meta:
model = Match
fields = ['id', 'teams']
class TeamSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Team
fields = ['id', 'name']
urls.py
router = DefaultRouter()
router.register(r'teams', TeamViewSet)
router.register(r'matches', MatchViewSet)
router.register(r'matchteams', MatchTeamViewSet)
urlpatterns = router.urls
视图是使用 ModelViewSets 定义的。
任何想法为什么会发生这种情况?
谢谢!
【问题讨论】:
标签: django django-rest-framework