【问题标题】:Django restframework: How serialize two models queryset?Django rest框架:如何序列化两个模型查询集?
【发布时间】:2018-03-10 13:47:11
【问题描述】:

我有以下情况:一个用户可以拥有多个个人资料。这是我的模型课。像这样的例子:

models.py:

class Profile:
    name=models.Charfield()

class UserProfile:
   user=models.ForeignKey(User)
   profile = models.ForeignKey(Profile)

serializers.py:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

这里我通过 JSON 返回我的所有用户,但我想添加一个名为 profiles 的新字段,它返回用户拥有的所有 ids 个人资料。

{ "id": 1,
  "name" : "John"
  ....
  profiles = [1, 2]
} 

如何获取(查询)用户拥有的所有配置文件并将它们添加到我的最终 JSON 中?

【问题讨论】:

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


    【解决方案1】:

    在 UserSerializer 上将字段配置文件声明为 PrimaryKeyRelatedField

    profiles = serializers.PrimaryKeyRelatedField()

    默认情况下,此字段是可读写的,尽管您可以使用 read_only 标志更改此行为。

    见docs

    【讨论】:

      【解决方案2】:

      1) 简化关系 - 在这种情况下只需要 User 和 Profile 模型,您不必在 UserProfile 表中存储显式关系,因为在 Profile 模型中也可以这样做,只要您不需要用户与其他用户共享个人资料。

      2) 创建 ProfileSerializer

      3) 使用 many=True 属性将配置文件字段添加到 UserSerializer 并在“源”属性中提供参考 请参考这些文档,因为它们非常好 http://www.django-rest-framework.org/api-guide/serializers/

      另外要提的是,创建 UserProfile 已被弃用,在新版本的 Django 中,您可以使用设置属性 AUTH_USER_MODEL 扩展基本用户模型

      【讨论】:

        猜你喜欢
        • 2016-01-25
        • 2014-12-19
        • 1970-01-01
        • 1970-01-01
        • 2016-04-07
        • 2012-11-16
        • 1970-01-01
        • 1970-01-01
        • 2018-01-01
        相关资源
        最近更新 更多