在Django中序列化外键对象 [英] Serializing Foreign Key objects in Django

查看:231
本文介绍了在Django中序列化外键对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在开发Django中的一些RESTful服务,与Flash和Android应用程序一起使用。

I have been working on developing some RESTful Services in Django to be used with both Flash and Android apps.

开发服务界面已经相当简单,但是我已经遇到了一个问题,即将具有外键和多对多关系的对象序列化。

Developing the services interface has been quite simple, but I have been running into an issue with serializing objects that have foreign key and many to many relationships.

我有一个这样的模型:

class Artifact( models.Model ):
    name                = models.CharField( max_length = 255 )
    year_of_origin      = models.IntegerField( max_length = 4, blank = True, null = True )
    object_type         = models.ForeignKey( ObjectType, blank = True, null = True )
    individual          = models.ForeignKey( Individual, blank = True, null = True )
    notes               = models.TextField( blank = True, null = True )

然后我将使用 select_related(),确保遵循外键关系:

Then I would perform a query on this model like this, using select_related(), to be sure that foreign key relationships are followed:

artifact = Artifact.objects.select_related().get(pk=pk)

一旦我有对象,我将其序列化,并将其传回给我的观点:

Once I have the object, I serialize it, and pass that back to my view:

serializers.serialize( "json", [ artifact ] )

这是我回来的请注意,外键(object_type和个人)只是其相关对象的id。

This is what I get back, note that the foreign keys (object_type and individual) are just the id's to their related objects.

[
      {
            pk: 1
            model: "artifacts.artifact"
            fields: {
                year_of_origin: 2010
                name: "Dummy Title"
                notes: ""
                object_type: 1
                individual: 1
            }
      }
]

这是非常好的,但是当使用 select_related()时我希望使用相关对象自动填充外键字段,而不仅仅是对象的id。

This is great, but what I was hoping for when using select_related() was that it would automatically populate the foreign key fields with the related object, not just the object's id.

我最近转换成Django,但投入了相当长的时间与CakePHP一起玩。

I am recent convert to Django, but put in a fair amount of time developing with CakePHP.

我对Cake ORM的真正喜欢是默认情况下会跟随关系并创建嵌套对象,当您调用查询时可以解除绑定关系。

What I really like about the Cake ORM was that it would follow the relationships and create nested objects by default, with the ability to unbind the relationships when you were calling your query.

这使得以不需要任何干预的方式抽象服务非常简单。

This made it very easy to abstract the services in a way that did not require any intervention on a case by case basis.

我看到,Django默认情况下不会这样做,但是有没有办法自动序列化一个对象及其所有的相关对象?任何提示或阅读都将不胜感激。

I see that Django does not do this by default, but is there a way to automatically serialize an object and all of it's related objects? Any tips or reading would be much appreciated.

推荐答案

我有一个类似的要求,虽然不是为了RESTful的目的。通过使用完整序列化模块,我能够实现所需要的,在我的情况下, Django Full Serializers 。这是 wadofstuff 的一部分,并根据新的BSD许可证分发。

I had a similar requirement although not for RESTful purposes. I was able to achieve what I needed by using a "full" serializing module, in my case Django Full Serializers. This is part of wadofstuff and is distributed under the new BSD license.

Wadofstuff使这很容易。例如在您的情况下,您需要执行以下操作:

Wadofstuff makes this quite easy. For e.g. in your case you'd need to do the following:

首先,安装wadofstuff。

First, install wadofstuff.

其次,添加以下设置到您的 settings.py 文件:

Second, add the following setting to your settings.py file:

SERIALIZATION_MODULES = {
    'json': 'wadofstuff.django.serializers.json'
}

第三,对用于序列化的代码稍作修改:

Third, make a slight change to the code used for serialization:

artifact = Artifact.objects.select_related().get(pk=pk)
serializers.serialize( "json", [ artifact ], indent = 4, 
    relations = ('object_type', 'individual',))

关键更改是关系关键字参数。唯一的(次要的)伎俩是使用形成关系的字段的名称而不是相关模型的名称。

The key change is the relations keyword parameter. The only (minor) gotcha is to use the name of the fields forming the relation not the names of the related models.

警告

文档


序列化模型时,Stuff序列化器的Wad与Django序列化程序100%兼容。

The Wad of Stuff serializers are 100% compatible with the Django serializers when serializing a model. When deserializing a data stream the the Deserializer class currently only works with serialized data returned by the standard Django serializers.

(加重)

希望这有帮助。

这篇关于在Django中序列化外键对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆