DRF嵌套json无法获取用户详细信息

时间:2019-07-12 02:37:57

标签: python-2.7 django-models django-rest-framework

我正在使用django rest框架,并正在建立组织和用户详细信息功能。我的模型,序列化器和模型视图集详细信息是这样的。

class OrganizationLatest(models.Model):
    name = models.CharField(max_length=500, blank=True, null=True)
    address = models.CharField(max_length=500, blank=True, null=True)
    user = models.ForeignKey(User, default="", null=True, blank=True)
    createdat = models.DateTimeField()
    updatedat = models.DateTimeField()

    class Meta:
        managed = False
        db_table = 'organization'

组织和用户序列化器如下

class organizationLatestSerializer(serializers.ModelSerializer):

    class Meta:
        model=OrganizationLatest
        fields =('name','address','user')

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('pk','username',)
        read_only_fields = ['id','username']

class OrganizationLatestVieset(viewsets.ModelViewSet):
       queryset = OrganizationLatest.objects.all()  # dummy objec
       serializer_class = organizationLatestSerializer

Rest api返回

[
    {
        "name": "Org1",
        "address": null,
        "user": 7
    },
    {
        "name": "Org2",
        "address": null,
        "user": 3
    },

]

但是我想要这种格式的JSON,

[
  {
    "name": "Org1",
    "address": "xxxxx",
    "user": [
      {
        "username": "jhon",
        "email": "a@g.com"
      }
    ]
  },
  {
    "name": "Org2",
    "address": "998,abc",
    "user": [
      {
        "username": "jhon",
        "email": "a@g.com"
      }
    ]
  }      
]

请让我知道如何实现预期的json格式。

谢谢大家

1 个答案:

答案 0 :(得分:1)

假设您所定义的 OrganizationLatest 模型,下面的代码段将提供所需的JSON,但是user字段将是一个对象,或者您可以将链接的用户的用户详细信息声明为{ {1}}实例。

OrganizationLatest

现在,您将在列表端点上获得输出json,如下所示:-


class OrganizationUserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('username','email',)
        read_only_fields = ['id','username']

class OrganizationLatestSerializer(serializers.ModelSerializer):
    user = OrganizationUserSerializer()
    class Meta:
        model=OrganizationLatest
        fields =('name','address','user')

class OrganizationLatestVieset(viewsets.ModelViewSet):
       queryset = OrganizationLatest.objects.all() 
       serializer_class = organizationLatestSerializer

  

注意,我不建议您更改[ { "name": "Org1", "address": "xxxxx", "user": { "username": "jhon", "email": "a@g.com" } }, { "name": "Org2", "address": "998,abc", "user": { "username": "jhon", "email": "a@g.com" } } ] 并使用它代替UserSerializer来在OrganizationUserSerializer中显示用户