我不确定您是否已解决此问题,但这对其他遇到此问题的人可能有用。除了重写HyperlinkedIdentityField和自己创建自定义序列化字段之外,您无能为力。这个问题的一个示例在下面的github链接中(以及一些源代码来解决):
https://github.com/tomchristie/django-rest-
framework/issues/1024
在此指定的代码是这样的:
from rest_framework.relations import HyperlinkedIdentityFieldfrom rest_framework.reverse import reverseclass 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中包含了类似内容(我还没有找到),但是上面的代码对我有用。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)