正文
在使用 Django-Rest-Framework 的 HyperlinkedIdentityField
来生成字段的反向链接时,如果数据库中字段的值为空,此时 DRF 就会返回一串错误信息:
django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
解决方案:
-
重写
HyperlinkedIdentityField
类的to_representation
方法,从而规避数据库值为空的情况注:
value
是一个数据库记录的对象- 需要将
user
修改为数据库中希望反向生成链接的字段名
# 重写 HyperlinkedIdentityField 类的 to_representation 方法,从而规避数据库值为空的情况 class MyHyperlinkedIdentityField(serializers.HyperlinkedIdentityField): def to_representation(self, value): if not value.user: return None return super().to_representation(value)
-
将序列化器中,对应字段的字段序列化类型修改为自己重写的子类
MyHyperlinkedIdentityField
class ScoreSerializer(serializers.ModelSerializer): uploadUser_href = MyHyperlinkedIdentityField( view_name='user-detail', lookup_field='User_id', lookup_url_kwarg='userID')