Django REST框架:嵌套对象可以在列表视图中访问其父对象的详细信息吗? [英] Django REST framework: Can a nested object access its parent object's details in a List View?

查看:167
本文介绍了Django REST框架:嵌套对象可以在列表视图中访问其父对象的详细信息吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个嵌套资源,其中一个字段取决于其父资源的值。

I am attempting to implement a nested resource where one of its fields depends on a value from its parent resource.

假设我们正在为一家公司建立一个系统提供有关其客户的信息以及公司销售人员的销售数据。因此,我们有两种型号,客户 Rep 。一个代表可以卖给多个客户。

Suppose we are building a system for a company which provides information about its customers plus sales figures for the company's salespeople. So we have two models, Customer and Rep. A rep can sell to more than one customer.

返回所有客户的URL: /api/1.0/customers /

URL that returns all customers: /api/1.0/customers/

特定客户的网址: /api/1.0/customers/123 /

特定销售代表的客户特定信息的网址: /api/1.0/customers/123/rep/9 /

URL for customer-specific information for a specific sales rep : /api/1.0/customers/123/rep/9/

请注意,rep URL包含客户ID以及代表ID。

Note the rep URL contains the customer ID as well as the rep ID.

我希望客户网址返回嵌套资源包含有关rep的摘要信息,以及该代表的完整客户特定信息的超链接。这是所有客户的URL的输出:

I want the customer URL to return a nested resource containing summary information about the rep, plus a hyperlink to full customer-specific information for that rep. This is the output from the URL for all customers:

[
    {
        "id": 100, 
        "customer_name": "DolManSaxLil",
        "rep": {
                "id": 4,
                "annual_sales": 1500.01,
                "name": "Fred",
                "url": "http://localhost:8000/api/1.0/customer/100/rep/4/"
               }
    },
    {
        "id": 200, 
        "customer_name": "Hotblack",
        "rep": {
                "id": 4,
                "annual_sales": 10500.42,
                "name": "Fred",
                "url": "http://localhost:8000/api/1.0/customer/200/rep/4/"
               }
    }
]

为了实现这个,我们定义两个序列化器:

To implement this we define two serializers:

class CustomerSummarySerializer(serializers.HyperlinkedModelSerializer):
    id = ...
    name = ...
    rep = RepSummarySerializer(read_only=True)

class RepSummarySerializer(serializers.HyperlinkedModelSerializer):
    id = ...
    annual_sales = ...
    name = ....
    url = serializers.SerializerMethodField('get_rep_url')

我遇到的问题是我不能解决如何从函数 RepSummarySerializer.get_rep_url 中访问当前的customer.id。在细节视图中,可以在 self.parent.obj 中保存客户:

The problem I am facing is that I cannot work out how to access the current customer.id from the function RepSummarySerializer.get_rep_url. It's possible in a Detail view as the customer is held in self.parent.obj:

def get_rep_url(self, obj):
    customer_id = self.parent.obj.id
    url = reverse('api_customer_rep', 
              kwargs={'customer_id': customer_id,
                      'rep_id': obj.id},
                      request=serializer.context.get('request'))
    return url

但是,在列表视图中, self.parent.obj 是Customer对象的QuerySet,我可以没有任何方式识别当前的客户。有什么办法吗我有没有想过明显的东西?

However, in a list view, self.parent.obj is a QuerySet of Customer objects and I can't see any way of identifying the current Customer. Is there any way of doing this? Have I missed something obvious?

推荐答案

清晰的时刻:解决方案是使用 SerializerMethodField 实例化 RepSummarySerializer ,并在上下文中传递 customer_id

Moment of clarity: the solution is to use a SerializerMethodField to instantiate the RepSummarySerializer and pass the customer_id in the context:

class CustomerSummarySerializer(serializers.HyperlinkedModelSerializer):
    id = ...
    name = ...
    rep = serializers.SerializerMethodField('get_rep')


    def get_rep(self, obj):
        rep = obj.rep
        serializer_context = {'request': self.context.get('request'),
                              'customer_id': obj.id}
        serializer = RepSummarySerializer(rep, context=serializer_context)
        return serializer.data

现在可以在 RepSummarySerializer.get_rep_url中访问 customer_id 如下:

The customer_id can now be accessed in RepSummarySerializer.get_rep_url like this:

def get_rep_url(self, obj):
    customer_id = self.context.get('customer_id')
    ...

不知道为什么我没有想到这三个小时前。

Don't know why I didn't think of this three hours ago.

这篇关于Django REST框架:嵌套对象可以在列表视图中访问其父对象的详细信息吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆