簡體   English   中英

Django restframework:如何序列化兩個模型queryset?

[英]Django restframework: How serialize two models queryset?

我有以下情況:用戶可以有多個配置文件。 這是我的模特課。 像這樣的例子:

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的新字段,返回用戶擁有的所有id配置文件。

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

如何獲取(查詢)用戶擁有的所有配置文件並將其添加到我的最終JSON中?

在UserSerializer上將字段配置文件聲明為PrimaryKeyRelatedField

profiles = serializers.PrimaryKeyRelatedField()

默認情況下,此字段是讀寫的,但您可以使用read_only標志更改此行為。

文檔

1)簡化關系 - 在這種情況下只需要User和Profile模型,您不必在UserProfile表中存儲顯式關系,因為可以在Profile模型中完成相同的操作,只要您不需要用戶與其他用戶。

2)創建ProfileSerializer

3)向UserSerializer添加配置文件字段,其中包含許多= True屬性並在'source'屬性中提供引用請訪問這些文檔,因為它們非常好http://www.django-rest-framework.org/api-guide/serializers/

另外需要提一下的是,創建UserProfile是一種描述,在新版本的Django中,您可以使用設置屬性AUTH_USER_MODEL擴展基本用戶模型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM