Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python django rest framework HyperlinkedEntityField具有多个查找参数_Python_Django_Django Rest Framework - Fatal编程技术网

Python django rest framework HyperlinkedEntityField具有多个查找参数

Python django rest framework HyperlinkedEntityField具有多个查找参数,python,django,django-rest-framework,Python,Django,Django Rest Framework,我的URL模式中有以下URL: url(r'^user/(?P<user_pk>[0-9]+)/device/(?P<uid>[0-9a-fA-F\-]+)$', views.UserDeviceDetailView.as_view(), name='user-device-detail'), 但是,我认为它失败了,因为URL有两个字段: django.core.exceptions.ImpropertlyConfigured:无法使用视图名称“用户设备详细信息”解析超

我的URL模式中有以下URL:

url(r'^user/(?P<user_pk>[0-9]+)/device/(?P<uid>[0-9a-fA-F\-]+)$', views.UserDeviceDetailView.as_view(), name='user-device-detail'),
但是,我认为它失败了,因为URL有两个字段:

django.core.exceptions.ImpropertlyConfigured:无法使用视图名称“用户设备详细信息”解析超链接关系的URL。您可能未能将相关模型包括在API中,或者在此字段上错误配置了
lookup\u字段
属性


当URL有两个或多个URL模板项时,如何使用
HyperlinkedEntityField
(或任何
Hyperlink*字段
)呢?(查找字段)?

我不确定您是否已解决此问题,但这可能对其他有此问题的人有用。除了重写HyperlinkedEntityField和自己创建自定义序列化器字段之外,您没有什么可以做的。下面的github链接就是这个问题的一个例子(以及一些解决这个问题的源代码):

此处指定的代码如下所示:

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)
url=ParameterizedHyperlinkedEntityField(查看用户设备详细信息),查找字段=((“”,'user\u-pk'),(“”,'uid'),只读=True)
其中
是模型字段,在您的案例中可能是'id'和'uid'


注意:上面的问题是两年前报道的,我不知道他们是否在较新版本的DRF中包含了类似的内容(我没有发现),但上面的代码对我很有用。

谢谢。我最终创建了自己的HyperlinkedEntityField子类,就像它只覆盖了“to_representation()”方法:def to_representation(self,value):return reverse('user-device-detail',kwargs={'user_-pk':value.owner_-id,'uid':value.uid},request=self.context['request'])将此标记为已接受,即使我尚未尝试。这似乎是一种处理问题的明智(且可扩展)方法。只有当您可以从
obj
(直接或间接)提取所有必要的密钥时,该解决方案才有效。不幸的是,在多对多依赖的情况下,这是不可能的。
url = ParameterisedHyperlinkedIdentityField(view_name="user-device-detail", lookup_fields=(('<model_field_1>', 'user_pk'), ('<model_field_2>', 'uid')), read_only=True)