在使用关系序列化模型时返回部分对象

时间:2017-08-26 17:23:00

标签: django django-rest-framework

所以我有两个模型FooBarFooBar有一对多的关系,如下所示。

应用/ models.py

class Foo(models.Model):
    id = models.IntegerField(primary_key=True)
    sourceid = models.IntegerField(blank=True, null=True)
    name = models.TextField(unique=True, null=True)
    url = models.TextField(unique=True, null=True)
    created_at = models.DateTimeField(default=datetime.datetime.utcnow, null=True)
    updated_at = models.DateTimeField(default=datetime.datetime.utcnow,null=True)

    class Meta:
        managed = False
        db_table = 'foo'

    class JSONAPIMeta:
        resource_name = 'foo'

class Bar(models.Model):
    id = models.IntegerField(primary_key=True)
    parent_foo = models.ForeignKey(Foo, models.DO_NOTHING, db_column='parentId')  # Field name made lowercase.
    url = models.TextField()
    extension = models.ForeignKey('self', models.DO_NOTHING, db_column='extensionId', blank=True, null=True) 
    created_at = models.DateTimeField(blank=True, null=True)
    updated_at = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'bar'

现在的问题是,我想创建一个将FooBarList嵌入Bar的序列化工具Foo

我已经通过以下代码轻松实现了这一目标:

应用/ serializers.py

class FooBarList(serializers.ModelSerializer):
    class Meta:
        model = Foo
        fields = ('id','name','url','created_at','updated_at','bar_set')

当我调用此序列函数时,问题就出现了......只有Bar对象的'id'参数显示在响应中。如下所示:

JSON输出

{
"data": [
    {
        "attributes": {
            "created_at": "2017-08-23T16:07:11.384209Z",
            "name": "TestFoo",
            "updated_at": "2017-08-23T17:41:17.179040Z",
            "url": "TestFoo.org"
        },
        "id": "1",
        "relationships": {
            "Bar": {
                "data": [
                    {
                        "id": "1",
                        "type": "Bar"
                    },
                    {
                        "id": "2",
                        "type": "Bar"
                    },
                ],
                "meta": {
                    "count": 2
                }
            }
        },
        "type": "Foo"
    },
    {
        "attributes": {
            "created_at": "2017-08-23T16:07:11.390343Z",
            "name": "TestFoo2",
            "updated_at": "2017-08-23T17:41:17.186193Z",
            "url": "TestFoo2.org"
        },
        "id": "2",
        "relationships": {
            "Bar": {
                "data": [
                    {
                        "id": "10",
                        "type": "Bar"
                    }
                ],
                "meta": {
                    "count": 1
                }
            }
        },
        "type":"Foo"
    }]}

从查看数据库中我可以看到ID是正确的,我认为这应该包括来自Bar对象的其他属性,例如'url'。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

Bar创建序列化程序,并在FooBarList序列化程序中提供。

class FooBarList(serializers.ModelSerializer):
   bar = BarSerializer(source='bar')

因此,相关的Bar实例可以序列化