Django Rest Framework, hyperlinking a nested relationship

前端 未结 2 1360
隐瞒了意图╮
隐瞒了意图╮ 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 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.

提交回复
热议问题