缺少基类django序列化程序的字段

时间:2018-04-16 14:50:19

标签: django serialization

我的课程很少:

class Correspondent(models.Model):
    title = models.CharField(max_length=60)

class Subject(models.Model):
    title = models.CharField(max_length=60)

class Letter(models.Model):
    correspondent = models.ForeignKey(Correspondent, 
    on_delete=models.SET_NULL, null=True)
    subject = models.ForeignKey(Subject, on_delete=models.SET_NULL, null=True)
    description = models.TextField(max_length=600, blank=True)
    case_number = models.CharField(max_length=100, blank=True)
    inventory_number = models.CharField(max_length=100, blank=True)
    note = models.TextField(max_length=300, blank=True)
    user = models.ForeignKey(User, editable=False, on_delete=models.SET_NULL, null=True)
    date = models.DateField(default=datetime.date.today)
    date_creation = models.DateTimeField(auto_now_add=True)

class IncomingLetter(Letter):
    response_to = models.ForeignKey('OutgoingLetter', on_delete=models.SET_NULL, null=True, blank=True)
    outgoing_number = models.CharField(max_length=120, blank=True)
    incoming_number = models.CharField(max_length=120, blank=True)


class OutgoingLetter(Letter):
    response_to = models.ForeignKey(IncomingLetter, on_delete=models.SET_NULL, null=True, blank=True)
    outgoing_number = models.CharField(max_length=120, blank=True)

并且在视图中我尝试使用序列化的B类实例发送json:

from django.http import JsonResponse
from django.core import serializers
from .models import IncomingLetter
def index(request):
   ....
   some_data = IncomingLetter.objects.all()
   serialized_data = serializers.serialize('json', some_data)
   return JsonResponse(json.dumps(serialized_data), safe=False)

并且响应错过了json中的所有Letter字段。有没有办法不手动序列化? serialized_data == {"model": "letters.incomingletter", "pk": 4, "fields": {"response_to": 3, "outgoing_number": "12312321", "incoming_number": "123123"}}

已解决#(不确定)

我编写了简单的序列化程序,但不确定这是最干净的方法(许多不必要的字段,但很容易清理):

class LetterSerializer:
    def __init__(self):
        self.serialized_data = {}

    def serialize(self, data):
        for idx, instance in enumerate(data):
            serialized_instance_data = {}
            for key, value in instance.__dict__.items():
                serialized_instance_data[key] = str(value)
            self.serialized_data[idx] = serialized_instance_data

        return self.serialized_data

0 个答案:

没有答案