【发布时间】:2015-01-14 16:32:09
【问题描述】:
我有一个引用Generic Relation 的模型,我想详细地对其进行序列化。
class AType(models.Model):
foo = CharField()
class BType(models.Model):
bar = PositiveIntegerField()
class ToSerialize(models.Model):
scope_limit = models.Q(app_label="app", model="atype") | \
models.Q(app_label="app", model="btype")
content_type = models.ForeignKey(ContentType, limit_choices_to=scope_limit)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
我希望 ToSerialize 视图集的 list 方法的 JSON 看起来像:
[
{
"atype": { "id": 1, "foo": "a" }
},
{
"atype": { "id": 2, "foo": "b" }
},
{
"btype": { "id": 1, "bar": "1" }
},
{
"btype": { "id": 2, "bar": "2" }
}
]
有没有一种方法可以让 ToSerialize 对象的视图集的序列化程序根据 content_type/object_id 产生“条件字段”来实现这种效果?
【问题讨论】:
标签: django django-rest-framework