gpt4 book ai didi

python - 如何使用序列化器获取 django 中的所有 related_name 字段?

转载 作者:行者123 更新时间:2023-12-01 09:00:48 25 4
gpt4 key购买 nike

这是我的 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)

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)

def __str__(self):
return self.name

这是我的seralizers.py

from rest_framework import serializers
from .models import *
from django.db.models import Sum,Avg,Max,Min,Count,F,Q

class CatalogSerializer(serializers.HyperlinkedModelSerializer):
dynamic_data = serializers.SerializerMethodField()
class Meta:
model = Catalog
fields = '__all__'

def get_dynamic_data(self, obj):
totalpieces = Catalog.objects.all().aggregate(total_pieces=Count('no_of_pcs'))
totalprice = Catalog.objects.all().aggregate(total_price=Sum('per_piece_price'))
return totalprice,totalpieces

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

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

这是我的观点.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

这是我的 urls.py

from django.conf.urls import url, include
from django.contrib import admin

from api import views
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework import routers

router = routers.DefaultRouter()
router.register('catalogs',views.CatalogView)
router.register('companies',views.CompanyView)
router.register('users',views.UserView)

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include(router.urls)),
]

我什么时候去 http://127.0.0.1:8000/companies/

我正在获取

     [
{
"name": "google",
"phone_number": 12,
"catalog": [
5
]
}
]

我期待这个..

     [
{
"url": "google",
"name": "google",
"phone_number": 123214214,
"catalog_details":[
"name": "sobhagya",
"no_of_pcs": 22,
"per_piece_price": "3567.00",
]
}
]

在这里,我只能获取我已设置为 foreignkKeyrelated_name 的 id,但我希望所有字段都像上面这样。请检查 json api 格式

谢谢

最佳答案

class CompanySerializer(serializers.ModelSerializer):
catalog = CatalogSerializer(many=True) # if you want many catalog objects connected to the company else many=False
class Meta:
model = Company
fields = ('name', 'phone_number', 'catalog','user')

您需要调用公司序列化器内部的目录序列化器来获取相关对象

关于python - 如何使用序列化器获取 django 中的所有 related_name 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52467339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com