Django REST Framework的HyperlinkedRelatedField是否无法引用多个kwargs的url模式?

时间:2016-06-01 14:47:21

标签: django-rest-framework

我有一个REST api url端点,代表Song中的Album

/api/album/(?P<album_id>)/song/(?P<id>)/

我希望从其他资源中引用它,例如Chart包含有史以来的前1000首歌曲。这是ChartSerializer的实现:

class ChartSerializer(HyperlinkedModelSerializer):
    songs = HyperlinkedRelatedField(
        queryset=Song.objects.all(),
        view_name='api:song-detail',
        lookup_field='id'
    )

    class Meta:
        model = Chart
        fields = ('songs', )

显然,我可以将id作为lookup_field传递,但在我看来,无论如何我都无法通过album_id。我正在研究HyperlinkedModelSerializer.get_url()方法:

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.
    """
    # Unsaved objects will not yet have a valid URL.
    if hasattr(obj, 'pk') and obj.pk in (None, ''):
        return None

    lookup_value = getattr(obj, self.lookup_field)
    kwargs = {self.lookup_url_kwarg: lookup_value}
    return self.reverse(view_name, kwargs=kwargs, request=request, format=format)

正如您所看到的,它从头构建反向URL查找的kwargs,并且不允许向其传递其他参数。我是对的,不支持这个吗?

更新: 在DRF的问题列表中找到了对此问题的引用:https://github.com/tomchristie/django-rest-framework/issues/3204

1 个答案:

答案 0 :(得分:0)

所以,答案是肯定的。在DRF文档中甚至有关于此问题的段落:

http://www.django-rest-framework.org/api-guide/relations/#custom-hyperlinked-fields