且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将具有反向一对一字段的django模型序列化为JSON

更新时间:2023-01-17 08:31:28

这个问题出现在我正在开发项目。在我们决定自己扩展Django序列化器之前,我们将要使用的解决方案。这应该适用于您的需要,但是。



为了解决这个问题,弄脏你的手,我会建议 wadofstuff的Django完整序列化程序



在使用Wiki解决您的示例将如下所示:



您需要向模型添加一个方法,该方法返回 QuerySet $ c $的python表示从django.db导入模型

  django.core导入序列化程序

class Patient(
name = models.CharField('Name',max_length = 50)

def extra_address(self):
return serializers.serialize('python' self.address.all())

class地址(models.Model):
town = models.CharField('Town / Village',max_length = 50)
patient = models.OneToOneField(Patient,related_name ='address')

然后,您可以将方法添加到更健壮的序列化程序采用的附加列表中。 >

  from django.core import serializers 
print serializers.serialize('json',Patient.objects.all(),extras = ('extra_address'))

一个 extras 键将被添加到字典中,并且将具有您需要的任何额外的信息。


Lets say I have the following two django (1.3) models

from django.db import models
class Patient(models.Model):
    name =  models.CharField('Name', max_length=50)

class Address(models.Model):
    town = models.CharField('Town/Village', max_length=50)
    patient = models.OneToOneField(Patient, related_name='address')

Now when i try to serialize a Patient model instance to JSON using django's serializers, the resulting JSON string does'nt have the address details with it (it's unable to traverse through the reverse direction of One-to-one relation)

This happens event if I use select_related('address') to populate the address object into the cache. i.e.

from django.core import serializers
>>> print serializers.serialize('json',[Patient.objects.select_related('address').get(id=1)])

Is there are way I can get around this problem?

This problem came up in the project I am currently developing. Here is the solution we were going to use before we decided to just extend the Django serializer ourselves. This should work just fine for your needs though.

To solve the problem with out getting your hands dirty I would recommend wadofstuff's Django Full Serializers.

After getting it setup using the wiki solving your example would look something like this:

You need to add a method to your model which returns a python representation of the QuerySet.

from django.db import models
from django.core import serializers
class Patient(models.Model):
    name =  models.CharField('Name', max_length=50)

    def extra_address(self):
        return serializers.serialize('python', self.address.all())

class Address(models.Model):
    town = models.CharField('Town/Village', max_length=50)
    patient = models.OneToOneField(Patient, related_name='address')

Then you can add the method to the list of extras taken by the more robust serializer.

from django.core import serializers
print serializers.serialize('json', Patient.objects.all(), extras=('extra_address',))

An extras key will be added to the dictionary and will have whatever extra pieces of information you needed in it.