栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

带有多个查找参数的django-rest-framework HyperlinkedIdentityField

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

带有多个查找参数的django-rest-framework HyperlinkedIdentityField

我不确定您是否已解决此问题,但这对其他遇到此问题的人可能有用。除了重写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中包含了类似内容(我还没有找到),但是上面的代码对我有用。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/652776.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号