python - 如何在 django rest 框架中获取外键字段名称而不是 id

标签 python django django-rest-framework

这是我的模型.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 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。与公司名称。 我想在 rest 框架中发布来自相同 api 的数据 谢谢,,

最佳答案

由于您在 Company 模型中定义了 __str__() 方法,您可以使用StringRelatedField()作为

class UserSerializer(serializers.ModelSerializer):
    <b>company_name = serializers.StringRelatedField()</b>
    class Meta:
        model = User
        fields = '__all__'


更新
覆盖 to_representation 方法

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

    <b>def to_representation(self, instance):
        rep = super(UserSerializer, self).to_representation(instance)
        rep['company_name'] = instance.company_name.name
        return rep</b>

关于python - 如何在 django rest 框架中获取外键字段名称而不是 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52491330/

相关文章:

python - 没有邮戳 API key 无法发送电子邮件

python - django 自定义登录 View 和 django 自定义身份验证后端之间的区别?

django - 处理 url 编码数据时 django rest 框架出现问题

django - 为什么 DjangoRF 序列化器 is_valid 是假的?

django - 您可以通过 django rest 框架在部分更新 django 对象时触发信号吗?

python - pypdf合并页面问题

python3将文件(从文件夹和子文件夹)转换为特定格式的json文件(项目包括文件夹名称和文件名)

python - Django 合并 2 个具有相同值的字典/查询集

python - 使用网格作为管理 UI 交互规则的框架

python - 让 Twisted 在后台工作