当前位置: 代码迷 >> python >> 如何在django rest框架中获取所有字段,该框架在带有外键的不同模型中被定义为相关名称?
  详细解决方案

如何在django rest框架中获取所有字段,该框架在带有外键的不同模型中被定义为相关名称?

热度:78   发布时间:2023-06-27 21:19:08.0

这是我的models.py

from __future__ import unicode_literals
from django.db import models

class User(models.Model):
    name = models.CharField(max_length=200)
    company_name = models.ForeignKey('Company',on_delete=models.CASCADE,related_name='user')

    def __str__(self):
        return self.name

class Company(models.Model):
    name = models.CharField(max_length=200)
    phone_number = models.IntegerField(null=True,blank=True)

    def __str__(self):
        return self.name

class Catalog(models.Model):
    name = models.CharField(max_length=200)
    no_of_pcs = models.IntegerField(null=True,blank=True)
    per_piece_price = models.DecimalField(null=True,blank=True,max_digits=10,decimal_places=2)
    company_name = models.ForeignKey(Company,on_delete=models.CASCADE,related_name='catalog')

    def __str__(self):
        return self.name

这是我的serializers.py

from rest_framework import serializers
from .models import *
from django.db.models import Sum,Count

class CatalogSerializer(serializers.ModelSerializer):
    total_pieces = serializers.SerializerMethodField()
    total_price = serializers.SerializerMethodField()
    company_name = serializers.CharField()

    class Meta:
        model = Catalog
        fields = ('name','no_of_pcs','per_piece_price','company_name','total_pieces','total_price')

    def get_total_pieces(self, obj):
        totalpieces = Catalog.objects.aggregate(total_pieces=Count('no_of_pcs'))
        return totalpieces["total_pieces"]

    def get_total_price(self, obj):
        totalprice = Catalog.objects.aggregate(total_price=Sum('per_piece_price'))
        return totalprice["total_price"]

class UserSerializer(serializers.ModelSerializer):
    company_name = serializers.CharField()
    class Meta:
        model = User
        fields = '__all__'

class CatalogData(serializers.ModelSerializer):
    class Meta:
        model = Catalog
        fields = ('name', 'no_of_pcs', 'per_piece_price')


class CompanySerializer(serializers.ModelSerializer):
    catalog = CatalogData(many=True)
    user = UserSerializer(many=True)
    class Meta:
        model = Company
        fields = ('name', 'phone_number', 'catalog','user')

这是我的views.py

from __future__ import unicode_literals
from django.http import HttpResponse
from .models import *
import json
from django.http import JsonResponse, HttpResponse
from .serializers import *
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets


class CatalogView(viewsets.ModelViewSet):
    queryset =  Catalog.objects.select_related('company_name')
    serializer_class = CatalogSerializer

class CompanyView(viewsets.ModelViewSet):
    queryset =  Company.objects.all()
    serializer_class = CompanySerializer

class UserView(viewsets.ModelViewSet):
    queryset =  User.objects.all()
    serializer_class = UserSerializer

我正在获得这样的api。

[
    {
        "name": "sarees",
        "no_of_pcs": 23,
        "per_piece_price": "33333.00",
        "company_name": "google",
        "total_pieces": 3,
        "total_price": 471118.0
    }
]

在这里,我仅获得公司模型的公司名称。 但我期望同一公司的所有字段名称。

但是我期望输出-

像这样:

[
    {
        "name": "sarees",
        "no_of_pcs": 23,
        "per_piece_price": "33333.00",
        "company": [
                {
                    "name": "google",
                    "phone_number": 323232
                }
            ],
        "total_pieces": 3,
        "total_price": 471118.0
    }
]

我想实现公司的所有领域。 与相同的API内的子列表

谢谢,

您可以为此使用器。 将序列化器更改为此:

class CompanySerializer(serializers.ModelSerializer):
    catalog = CatalogData(many=True)
    user = UserSerializer(many=True)
    class Meta:
        model = Company
        fields = ('name', 'phone_number', 'catalog','user')

class CatalogSerializer(serializers.ModelSerializer):
    total_pieces = serializers.SerializerMethodField()
    total_price = serializers.SerializerMethodField()
    company = CompanySerializer(source='company_name') 

    class Meta:
        model = Catalog
        fields = ('name','no_of_pcs','per_piece_price','company','total_pieces','total_price')
        depth = 1