如何在Django Rest框架中获取ID的外键字段名称insted

时间:2018-09-25 05:46:41

标签: python django django-rest-framework

这是我的模特。py

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class Popupright extends React.Component {

popupnewshow = (e) => {
let ids = e.target.getAttribute("id") + "text";
console.log(ids)
let elements = document.getElementsByClassName('poprighttext showtext');
while(elements.length > 0){
  elements[0].classList.remove('showtext');
};
  document.getElementById(ids).classList.toggle("showtext");
};

render() {
  return (
    <div>
       <table className="table-bordered">
         <tbody>
          <tr className="table-samewidth">
            <td className="td-general"><button className="popup" id="xxx" onClick={this.popupnewshow}><div className="popuptitle">xxx</div></button></td>
          </tr>
          <tr className="table-samewidth">
            <td className="td-general"><button className="popup" id="yyy" onClick={this.popupnewshow}><div className="popuptitle">yyy</div></button></td>
          </tr>
          <tr className="table-samewidth">
            <td className="td-general"><button className="popup" id="zzz" onClick={this.popupnewshow}><div className="popuptitle">zzz</div></button></td>
          </tr>
        </tbody>
      </table>

      <div id="xxxtext" className="poprighttext">
          <p>xxx.</p>
      </div>
      <div id="yyytext" className="poprighttext">
          <p>yyy</p>
      </div>
      <div id="zzztext" className="poprighttext">
          <p>zzz</p>
      </div>
    </div>
  );
 }
}


export default Popupright;

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

这是我的views.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__'

我正在获得这样的api。 在这里,我得到的是id而不是company_name。

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

但是我期望输出-

像这样:

[
    {
        "id": 1,
        "name": "soubhagya",
        "company_name": 1
    },
    {
        "id": 2,
        "name": "nihar",
        "company_name": 2
    }
]

我期望我的api这样。与company_name。 我想在其余框架中发布来自相同api的数据 谢谢,

4 个答案:

答案 0 :(得分:2)

class UserSerializer(serializers.ModelSerializer):
    company_name = serializers.SerializerMethodField(source='get_company_name')
    class Meta:
        model = User
        fields = '__all__'
    def get_company_name(self, obj):
        return obj.company_name.name

答案 1 :(得分:2)

简单的解决方案是使用source

class UserSerializer(serializers.ModelSerializer):
    company_name = serializers.CharField(source='company_name.name')

答案 2 :(得分:1)

由于您已在 import sys from PyQt4.QtCore import * # Python Qt4 bindings for GUI objects from PyQt4.QtGui import * from math import * # For fun log() import numpy as np from matplotlib.figure import Figure # For Matplotlib Figure Object import matplotlib.pyplot as plt from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from mpl_toolkits.mplot3d import Axes3D class ThreeDSurface_GraphWindow(FigureCanvas): #Class for 3D window def __init__(self): self.fig =plt.figure(figsize=(7,7)) FigureCanvas.__init__(self, self.fig) #creating FigureCanvas self.axes = self.fig.gca(projection='3d')#generates 3D Axes object self.axes.hold(False)#clear axes on each run self.setWindowTitle("Main") # sets Window title def DrawGraph(self, x, y, z):#Fun for Graph plotting self.axes.clear() self.axes.plot_surface(x, y, z) #plots the 3D surface plot self.draw() class TabConfigWidget(QWidget):# The QWidget in which the 3D window is been embedded def __init__(self, parent=None): super(TabConfigWidget, self).__init__(parent) self.Combo=QComboBox()#ComboBox for change index self.Combo.addItems(['Graph1','Graph2'])#add indexes to ComboBox self.Combo.currentIndexChanged.connect(self.IndexChanged)#Invokes Fun IndexChanged when current index changes self.ThreeDWin = ThreeDSurface_GraphWindow()#creating 3D Window MainLayout = QGridLayout()# Layout for Main Tab Widget MainLayout.setRowMinimumHeight(0, 5) #setting layout parameters MainLayout.setRowMinimumHeight(2, 10) MainLayout.setRowMinimumHeight(4, 5) MainLayout.addWidget(self.Combo, 1, 1)#add GroupBox to Main layout MainLayout.addWidget(self.ThreeDWin,2,1)#add 3D Window to Main layout self.setLayout(MainLayout) #sets Main layout x=np.linspace(-6,6,30) #X coordinates y=np.linspace(-6,6,30) #Y coordinates X,Y=np.meshgrid(x,y) #Forming MeshGrid Z=self.f(X,Y) self.ThreeDWin.DrawGraph(X,Y,Z)#call Fun for Graph plot def f(self,x,y):#For Generating Z coordinates return np.sin(np.sqrt(x**2+y**2)) def IndexChanged(self):#Invoked when the ComboBox index changes x = np.linspace(np.random.randint(-5,0), np.random.randint(5,10), 40) #X coordinates y = np.linspace(np.random.randint(-5,0), np.random.randint(5,10), 40) #Y coordinates X, Y = np.meshgrid(x, y) #Forming MeshGrid Z = self.f(X, Y) self.ThreeDWin.DrawGraph(X, Y, Z) #call Fun for Graph plot class GSPP(QTabWidget): #This is the Main QTabWidget def __init__(self, parent=None): super(GSPP, self).__init__(parent) self.tab1 = TabConfigWidget() self.addTab(self.tab1, "Tab1 ") #adding the QWidget def Refresh(self): #Fun to refresh return if __name__ == '__main__': #The Fun for Main() app = QApplication(sys.argv) Window = GSPP() Window.setWindowTitle("Main") qr = Window.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) Window.move(qr.topLeft()) Window.showMaximized() app.processEvents() sys.exit(app.exec_()) 模型中定义了 __str__() 方法,因此可以将StringRelatedField()用作

Company


更新
覆盖 class UserSerializer(serializers.ModelSerializer): company_name = serializers.StringRelatedField() class Meta: model = User fields = '__all__' 方法

to_representation

答案 3 :(得分:0)

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