Django Rest Framework中有多个模型? [英] Multiple Models in Django Rest Framework?

查看:65
本文介绍了Django Rest Framework中有多个模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Django Rest框架。我想序列化多个模型并作为响应发送。目前,每个视图只能发送一个模型(例如下面的 CartView 仅发送Cart对象)。

I am using Django Rest framework. I want to serialize multiple models and send as response. Currently I can send only one model per view(like CartView below sends only Cart object). Following models(unrelated) can be there.

class Ship_address(models.Model):
   ...

class Bill_address(models.Model):
   ...

class Cart(models.Model):
   ...

class Giftwrap(models.Model):
   ...

我尝试使用<一个href = https://github.com/Axiologue/DjangoRestMultipleModels rel = noreferrer> DjangoRestMultiplemodels ,它可以正常工作,但有一些限制。有内置的方法吗?我不能追加到在以下视图中创建的序列化程序吗?

I tried using DjangoRestMultiplemodels, it works ok but has some limitations. Is there any in-built way ? Can't I append to the serializer that's created in the following view ?

from rest_framework.views import APIView

class CartView(APIView):
    """
    Returns the Details of the cart
    """

    def get(self, request, format=None, **kwargs):
        cart = get_cart(request)
        serializer = CartSerializer(cart)
        # Can't I append anything to serializer class like below ??
        # serializer.append(anotherserialzed_object) ??
        return Response(serializer.data)

我真的很喜欢DRF。但是,这种用例(发送多个对象)使我想到编写一个简单的旧Django视图是否更适合这种需求。

I really like DRF. But this use-case(of sending multiple objects) makes me think if writing a plain old Django view will be better suited for such a requirement.

推荐答案

您可以对其进行自定义,也不会太奇怪,因为它是 APIView (而不是 ModelViewSet ,人类会期望GET返回单个模型),例如您可以在GET响应中返回来自不同模型的多个对象

You can customize it, and it wouldn't be too weird, because this is an APIView (as opposed to a ModelViewSet from which a human being would expect the GET to return a single model) e.g. you can return several objects from different models in your GET response

def get(self, request, format=None, **kwargs):
    cart = get_cart(request)
    cart_serializer = CartSerializer(cart)
    another_serializer = AnotherSerializer(another_object)

    return Response({
        'cart': cart_serializer.data,
        'another': another_serializer.data,
        'yet_another_field': 'yet another value',
    })

这篇关于Django Rest Framework中有多个模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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