简体   繁体   中英

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.

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.

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

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

in 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. So, I tried to write a MethodField in serializers.py. I am not able to get any reasonable URL here, the only solution would be to hardcode it.

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? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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