我不确定您是否已经解决了这个问题,但这可能对遇到此问题的其他人有用。除了覆盖 HyperlinkedIdentityField 并自己创建自定义序列化程序字段之外,您无能为力。这个问题的一个例子是在下面的 github 链接中(连同一些源代码来解决它):
https://github.com/tomchristie/django-rest-framework/issues/1024
那里指定的代码是这样的:
from rest_framework.relations import HyperlinkedIdentityField
from rest_framework.reverse import reverse
class ParameterisedHyperlinkedIdentityField(HyperlinkedIdentityField):
"""
Represents the instance, or a property on the instance, using hyperlinking.
lookup_fields is a tuple of tuples of the form:
('model_field', 'url_parameter')
"""
lookup_fields = (('pk', 'pk'),)
def __init__(self, *args, **kwargs):
self.lookup_fields = kwargs.pop('lookup_fields', self.lookup_fields)
super(ParameterisedHyperlinkedIdentityField, self).__init__(*args, **kwargs)
def get_url(self, obj, view_name, request, format):
"""
Given an object, return the URL that hyperlinks to the object.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf.
"""
kwargs = {}
for model_field, url_param in self.lookup_fields:
attr = obj
for field in model_field.split('.'):
attr = getattr(attr,field)
kwargs[url_param] = attr
return reverse(view_name, kwargs=kwargs, request=request, format=format)
这应该有效,在您的情况下,您可以这样称呼它:
url = ParameterisedHyperlinkedIdentityField(view_name="user-device-detail", lookup_fields=(('<model_field_1>', 'user_pk'), ('<model_field_2>', 'uid')), read_only=True)
<model_field_1> 和 <model_field_2> 是模型字段,在您的情况下可能是“id”和“uid”。
请注意,上述问题是 2 年前报告的,我不知道他们是否在较新版本的 DRF 中包含类似的内容(我还没有找到),但上面的代码对我有用。