简体   繁体   English

Django REST:将URL序列化为类别的对象列表

[英]Django REST: serialize url to list of objects of a category

Hard facts: I am using Django 2.0 with python 3.6, if it makes any difference. 硬事实:如果有任何区别,我将Django 2.0与python 3.6结合使用。

What I am trying to achieve is a link to a list of objects that belong to a summary. 我试图实现的是指向属于摘要的对象列表的链接。 I have a ManyToOne relationship in my models.py. 我的models.py中有一个ManyToOne关系。

class Summary(models.model):
  type=models.CharField

class Object(models.Model):
  summary= models.ForeignKey(Summary, on_delete=models.CASCADE)

in urls.py 在urls.py中

object_list= views.ObjectListViewSet.as_view({
    'get': 'list'
})
urlpatterns = format_suffix_patterns([
    url(r'^summary/(?P<pk>[^/.]+)/objects/$', object_list, name='summary-objects')
])

and now the idea was to give a user the possibility to click the an url in the browsable API and getting all objects. 现在的想法是让用户可以单击可浏览API中的url并获取所有对象。 So, I tried to write a MethodField in serializers.py. 因此,我尝试在serializers.py中编写一个MethodField。 I am not able to get any reasonable URL here, the only solution would be to hardcode it. 我在这里无法获得任何合理的URL,唯一的解决方案是对其进行硬编码。

class SummarySerializer(serializers.HyperlinkedModelSerializer):
    url = serializers.HyperlinkedIdentityField(
        view_name="app:summary-detail")

    objects= serializers.SerializerMethodField('get_obj_url')

    def get_obj_url(self, obj):
        pass

    class Meta:
        model = Summary

Is this possible? 这可能吗? Is it necessary to write a MethodField? 是否有必要编写MethodField? If yes, how do I get the url I need? 如果是,如何获取所需的网址?

Actually, reverse, as suggested in the comments, does the trick. 实际上,按照注释中的建议,反向可以解决问题。 The solution is: 解决方案是:

def get_obj_url(self, obj):
    request = self.context.get('request')
    return request.build_absolute_uri(reverse('api-root')) + 'summary/{id}/objects'.format(
        id=obj.id)

EDIT:Typo 编辑:错别字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM