【问题标题】:Efficiently serializing multiple objects that need to make REST call高效序列化多个需要进行 REST 调用的对象
【发布时间】:2021-12-02 08:45:13
【问题描述】:

假设我有一个简单的模型,Account,如下:

    class Account(models.Model):
        name = models.CharField(db_index=True)

还有一个AccountSerializer,如下:

    class AccountSerializer(serializers.ModelSerializer):
        name = CharField(source="account.name")
        def _get_favorite_color(self, obj: Account):
            # Make a rest call to get this account's favorite color
            favorite_color = _get_favorite_color(name)

我还有一个ViewSet 和一个list 操作来获取所有帐户,还有一个Serializer 来序列化每个项目。返回的JSON 具有以下形状:

{
    'accounts':[
        {'name':'dave', 'favorite_color':'blue'},
        {'name':'john', 'favorite_color':'black'},
    ]
}

“批量”获取这些最喜欢的颜色的 django-esque 方式是什么?这个用于获取喜爱颜色的REST 调用可以将所有帐户ids 的列表作为输入并将它们返回到一个列表中,从而避免在只有一个人可以做的情况下进行n REST 调用。

这种逻辑在哪里最有意义?考虑到它一次只处理一个对象,我不能把这个逻辑放在Serializer 中。除了ViewSet,还有其他地方可以放置它吗?我的理解是ViewSets 应该尽可能精简。

【问题讨论】:

  • 视图集使用序列化器,因此使用视图集获取序列化器所需的内容并将其传递给 IMO 是有意义的
  • @BrianDestura 我明白了,所以你的意思是ViewSet 应该进行这个REST 调用,它会将这些项目的列表传递给Serializer,以便它可以为它序列化的每个项目正确设置此字段?
  • 是的!其余调用的结果可以传递给序列化程序上下文

标签: python django django-models django-rest-framework django-views


【解决方案1】:

您可以在 Account Viewset 中使用 action decorator 来获取数据,您可以在其中通过 url args 传递帐户 ID。

@action(methods=['GET'], detail=False, url_name='favourite_color')
    def favourite_color(self, request, pk=None):
        account_ids = list(request.query_params.get('account_ids').split(","))
        queryset = Account.objects.filter(id__in=account_ids).values('favourite_color')
        # Not sure how favourite color is linked to account
        # You will get the values hitting one query, and you can make a json response which needs to be returned

        return Response(json_response_of_favourite_colors)
    

Url 有点像这样:

网址:accounts/favourite_color/?account_ids=1,2,3

【讨论】:

    猜你喜欢
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    相关资源
    最近更新 更多