【问题标题】:DRF - Could not resolve URL for hyperlinked relationship using view name "matchteam-detail"DRF - 无法使用视图名称“matchteam-detail”解析超链接关系的 URL
【发布时间】: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


    【解决方案1】:

    您需要router.register 的第三个参数,然后它会为您提供matchteam-detail

    router = DefaultRouter()
    router.register(r'teams', TeamViewSet, 'teams')
    router.register(r'matches', MatchViewSet, 'matches')
    router.register(r'matchteams', MatchTeamViewSet, 'matchteams')
    

    我不知道你为什么现在需要这个,但你确实需要。它让我进行了 django 1 -> 2 迁移。也踢了我的牙。

    【讨论】:

    • 添加了该代码并得到了相同的错误,现在“matchteam-detail”没有出现在 urlpatterns 中:[^/.]+ )/$' [name='matchteams-detail']>, [^/.]+)\.(?P[a-z0-9]+ )/?$' [name='matchteams-detail']>
    【解决方案2】:

    不知道为什么,但删除:

    teams = serializers.HyperlinkedRelatedField(
        read_only=True,
        view_name='matchteam-detail',
    )
    

    来自 serializers.py 的作品!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-25
      • 2018-11-22
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 2019-09-15
      相关资源
      最近更新 更多