...
{
fields:
{
uat_date: "2015-07-25",
statu: "CG",
name: "慢赢优化",
tester: [
1
],
product_manager: 1,
module: [
2,
3
],
project: 1,
plan_version: 1,
publish_date: "2015-07-25",
actual_version: 1,
type: "XQ",
developer: [
1
]
},
model: "amazingTable.content",
pk: 1
}
...
...
{
fields:
{
uat_date: "2015-07-25",
statu: "CG",
name: "慢赢优化",
tester:
[
[
"kevin"
]
],
product_manager:
[
"kevin"
],
module:
[
[
"closewebbus",
"我是描述"
],
[
"xckhapp",
"我是描述"
]
],
project: 1,
plan_version: 1,
publish_date: "2015-07-25",
actual_version: 1,
type: "XQ",
developer: [
[
"kevin"
]
]
},
model: "amazingTable.content",
pk: 1
}
...
我序列化的是Content表,它含有一个外键关联的是Module表,1对多
我要先序列化Module表,然后序列化Content表的时候才可以使用到Module的真实值
class ModuleManager(models.Manager):
def get_by_natural_key(self, name, description):
return self.get(name = name, description = description)
class Module(models.Model):
objects = ModuleManager()
name = models.CharField(max_length=100, unique=True)
description = models.CharField(max_length=100, blank=True, null=True)
# natual_key的序列化
def natural_key(self):
return (self.name, self.description)
# natual_keys的解序列化
class Meta:
unique_together = (('name', 'description'),)
jsons = serializers.serialize('json', queryset,use_natural_foreign_keys=False)
jsons = serializers.serialize('json', queryset,use_natural_foreign_keys=True)
如果要给Content表序列化,那么要使用到外键的actual_key,要保证外键先序列化,如下依赖:
class Content(models.Model):
name = models.CharField(max_length=100)
...
module = models.ManyToManyField('Module')
def natural_key(self):
return (self.name,) + self.module.natural_key()
# 和"def"同缩进
natural_key.dependencies = ['example_app.module']