如何使用 Django Rest Framework ListAPIView 包含相关模型

How to include related models using Django Rest Framework ListAPIView

有 2 个模型,我需要一个列表,一个列表查询集,它将结合 2 个模型中的所有相关字段。

class Product(models.Model):
     name = models.CharField(...)
     price= models.Decimal(...)
     image = models.ImageField(...)
     description2 = models.TextField(....)

class Order(models.Model):
     buyer = models.CharField(...)
     product = models.ForeignKey(Product, on_delete=models.CASCADE)

拥有 return 包含完整相关模型的东西。具有此结果的 ORDER 查询集列表

   {
    "id": 1,
    "buyer": 1,       
    "product": 3,
    "name": "Product 1",
    "image": "url",
    "price": 10.50
  },
  {
    "id": 2,
    "buyer": 2,       
    "product": 2,
    "name": "Product 2",
    "image": "url",
    "price": 6.50
  },

{
    "id": 1,
    "buyer": 1,       
    "product": [
    {
       'id': 1,
       'name': 'Product 1',
       'image': "url",
       'price': 10.50
    }], 
  },
  {
    "id": 2,
    "buyer": 2,       
    "product": [
    {
       'id': 2,
       'name': 'Product 2',
       'image': "url",
       'price': 6.50
    }], 
}

这可能吗?

首先,您需要在 serializers.py 文件中定义序列化程序。

from rest_framework import serializers
from .models import Product, Order

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        fields = "__all__"
        model = Product

class OrderSerializer(serializers.ModelSerializer):
    product = ProductSerializer(read_only = True)
    
    class Meta:
        fields = ("buyer", "product", )
        model = Order

然后,您需要在 views.py 文件中为订单创建 ListAPIView。

from rest_framework import generics, mixins
from .models import Order
from .serializers import OrderSerializer

class OrderView(mixins.ListModelMixin, generics.GenericAPIView):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer

    def get(self, request, *args, **kwargs):
         return self.list(request, *args, **kwargs)

最后你需要在urls.py,

中添加api url
from .views import *
urlpatterns = [
    path('orders', OrderView.as_view(), name="order")
]

希望对您有所帮助。