Django Restframework,前向关系序列化

时间:2014-02-13 15:47:09

标签: django django-rest-framework

我有以下型号:

class GO_BIDS(models.Model):

    GO = models.ForeignKey(GO_PROFILE)
    GO_money = models.CharField()
    GO_currency = models.CharField()

class GO_PROFILE(models.Model):

    User = models.ForeignKey(User)
    Name = models.CharField()
    Photo = models.CharField()
    Phone = models.CharField()

我的Serializers看起来像这样:

class GO_PROFILESerializer(serializers.ModelSerializer):

    class Meta:
        model = GO_PROFILE
        fields = ('Name', 'Photo')


class GO_BIDSSerializer(serializers.ModelSerializer):

    gprofile = GO_PROFILESerializer(required=True)

    class Meta:
        model = GO_BIDS
        fields = ('id','GO_money','GO_currency','gprofile')

我想得到以下结构:

"GO_BIDS": [
            {
                "id": 3, 
                "GO": {
                    "Name":  "Steve", 
                    "Photo": "myphoto.png", 
                }, 
                "GO_money": "12.00", 
                "GO_currency": "USD", 
        }]

我一直在'GO_BIDS'对象没有属性'gprofile'。 有什么想法吗?

由于

1 个答案:

答案 0 :(得分:0)

听起来你想要一个Nested Relationship。您的GO_BIDS模型没有gprofile属性。试试这个:

class GO_BIDSSerializer(serializers.ModelSerializer):
    GO = GO_PROFILESerializer()

    class Meta:
        model = GO_BIDS
        fields = ('id','GO_money','GO_currency','GO')