Django外键模型无法在视图JSON中显示

时间:2018-05-30 03:05:30

标签: django python-3.x

当我运行此程序时,我收到JSON文件,但不包括外键(联系号码),我想显示一个联系人姓名/地址/电子邮件,其中包含多个联系号码。

models.py

 from django.db import models

class PhoneBook(models.Model):
    name = models.CharField(max_length=50)
    address = models.CharField(max_length=100, default='address')
    email = models.CharField(max_length=50, default='email')
    note = models.CharField(max_length=100, default='note')
    def __str__(self):  
        return self.name



class ContactNumber(models.Model):  
    number = models.ForeignKey(PhoneBook, related_name="contact_numbers")
    contact_number= models.CharField(max_length=30)

    def __str__(self):  
        return self.contact_number

views.py

  from django.shortcuts import render
from .models import PhoneBook,ContactNumber
from django.http import JsonResponse
from django.views import View

class PhoneBookList(View):
    def get(self,request):
        phonebooklist=list(PhoneBook.objects.values())
        return JsonResponse(phonebooklist,safe=False)

admin.py

from django.contrib import admin
from .models import PhoneBook,ContactNumber

class ContactNumberInline(admin.StackedInline):
    model = ContactNumber

class PhoneBookAdmin(admin.ModelAdmin):
    inlines =[
        ContactNumberInline,
    ]

admin.site.register(PhoneBook)
admin.site.register(ContactNumber)

结果: enter image description here

1 个答案:

答案 0 :(得分:0)

我或许可以用这种方法回答。

class PhoneBook(models.Model):
    ....

    def to_json(self):

        contact_numbers = [c.contact_number 
                     for c in self.contact_numbers.all()]

        return { 
            'name':            self.name, 
            'email':           self.email, 
            'address':         self.address,
            'note':            self.note,
            'contact_numbers': contact_numbers
        }

在您看来。

class PhoneBookList(View):
    def get(self,request):
        phonebooklist = PhoneBook.objects.all()
        serialized_data = [pb.to_json() for pb in phonebooklist]
        return JsonResponse(serialized_data, safe=False)

虽然有点肮脏的解决方案