Django Rest Framework, hyperlinking a nested relationship

前端 未结 2 1357
隐瞒了意图╮
隐瞒了意图╮ 2021-02-04 17:24

I\'ve got two models: User and Ticket. Ticket has one User, User has many Tickets

相关标签:
2条回答
  • 2021-02-04 17:51

    For the record, here is an example of the full solution based on Joe Holloway's answer:

    from rest_framework.reverse import reverse
    
    class WorkProjectSerializer(serializers.CustomSerializer):
       issues = drf_serializers.SerializerMethodField()
    
        def get_issues(self, obj):
            request = self.context.get('request')
            return request.build_absolute_uri(reverse('project-issue-list', kwargs={'project_id': obj.id}))
    
        class Meta:
            model = WorkProject
            fields = '__all__'
    
    0 讨论(0)
  • 2021-02-04 18:03

    You can use a SerializerMethodField to customize it. Something like this:

    class UserSerializer(serializers.HyperlinkedModelSerializer):
        tickets = serializers.SerializerMethodField('get_tickets')
    
        def get_tickets(self, obj):
            return "http://127.0.0.1:8000/users/%d/tickets" % obj.id
    
        class Meta:
            model = MyUser
            fields = ('id', 'nickname', 'email', 'tickets')
    

    I hard-wired the URL in there for brevity, but you can do a reverse lookup just as well. This basically just tells it to call the get_tickets method instead of the default behavior in the superclass.

    0 讨论(0)
提交回复
热议问题