gpt4 book ai didi

python - 基于外键django rest框架序列化数组数据

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:05 25 4
gpt4 key购买 nike

我正在使用 django rest 框架将 property_id 作为外键发布到收藏夹表中,并基于外键我想从属性表中获取所有字段。

class Favorites(models.Model):
"""Store favorite property"""

user_id = models.ForeignKey(User, on_delete=models.CASCADE)
property_id = models.ForeignKey(Property, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True, blank=True)

序列化器:

class FavoriteSerializer(serializers.ModelSerializer):
"""Favorite Properties serializer"""

class Meta:
model = Favorites
fields = ('user_id','property_id', )

View 集:

class FavoriteViewSet(viewsets.ModelViewSet):

http_method_names = ['get','post' ]
serializer_class = FavoriteSerializer
queryset = Favorites.objects.all()

输出: enter image description here

这是我的第一个输出。然后我同步我的属性 Serializer 并得到这个:

enter image description here

这是我需要的输出,但在发布过程中会产生问题。在发布期间我只需要 user_id 和 property_id 但它使我的发布形式如下:

enter image description here

有什么建议可以实现我的结果吗?

最佳答案

序列化器.py

class FavoriteCreateSerializer(serializers.ModelSerializer):
"""Favorite Properties serializer"""

class Meta:
model = Favorites
fields = ('user_id','property_id', )

class FavoriteListSerializer(serializers.ModelSerializer):
property_id = PropertySerializer(read_only=True)

class Meta:
model = Favorites
fields = ('user_id','property_id', )

View .py

class FavoriteViewSet(viewsets.ModelViewSet):

http_method_names = ['get','post' ]
serializer_class = FavoriteSerializer
queryset = Favorites.objects.all()

def get_serializer_class(self):
if self.action == 'create':
return FavoriteCreateSerializer
else:
return self.serializer_class

关于python - 基于外键django rest框架序列化数组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46798413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com