如何在Django睡觉框架中获取外键字段名而不是id
问题描述
这是我的模型。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
这是我的序列化程序.py
from rest_framework import serializers
from .models import *
from django.db.models import Sum,Count
class UserSerializer(serializers.ModelSerializer):
# name = serializers.StringRelatedField()
# company_name = serializers.CharField()
class Meta:
model = User
fields = '__all__'
这是我的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 UserView(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
我是这样得到API的.. 这里我得到的是id,而不是company_name。
[
{
"id": 1,
"name": "soubhagya",
"company_name": 1
},
{
"id": 2,
"name": "nihar",
"company_name": 2
}
]
但我期待的是输出--
这样:
[
{
"id": 1,
"name": "soubhagya",
"company_name": "google"
},
{
"id": 2,
"name": "nihar",
"company_name": "facebook"
}
]
我期待我的API是这样的。使用COMPANY_NAME。 我想把同一个接口的数据发布到睡觉框架 谢谢,
解决方案
由于您已在Company
模型中定义了__str__()
方法,因此可以将StringRelatedField()
用作
class UserSerializer(serializers.ModelSerializer):
company_name = serializers.StringRelatedField()
class Meta:
model = User
fields = '__all__'
更新
重写to_representation
方法
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
def to_representation(self, instance):
rep = super(UserSerializer, self).to_representation(instance)
rep['company_name'] = instance.company_name.name
return rep
相关文章