Django REST framework foreignkey 序列化

Django REST framework is a powerful and flexible toolkit for building Web APIs.

Some reasons you might want to use REST framework:

之前虽然也用了Django REST framework 但是序列化函数基本都是自己写的,并没有用框架带的序列化函数。这次不想在搞的那么麻烦,于是使用Django REST framework带的序列化函数。

但是在序列化foreignkey的时候却发现只有id,其余的数据没有。

model定义:

class PlayerGoodsItem(models.Model):
    create = models.DateTimeField(default=timezone.now, help_text='创建时间')
    update = models.DateTimeField(auto_now=True, help_text='修改时间')
    goods_item = models.ForeignKey(GoodsItem, related_name='goodsitem_playergoodsitem', help_text='商品信息',
                                   on_delete=models.CASCADE)

序列化代码:

class PlayerGoodsItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = PlayerGoodsItem
        fields = "__all__"

返回数据:

{
	"id": 7,
	"create": "2019-12-03T14:14:34.934473+08:00",
	"update": "2019-12-03T14:14:35.052401+08:00",
	"goods_item": 1
}

官方文档里只有反向序列化代码, 没有说如何进行foreignkey序列化。上网搜了一下,发现了这么两个帖子:

https://blog.csdn.net/WanYu_Lss/article/details/82120259

https://www.cnblogs.com/pgxpython/articles/10144398.html

看了下实现方法,觉得貌似不应该这么复杂,于是就尝试将foreignkey直接放进去序列化,事实证明是可以的,修改后的序列化函数

class GoodsItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsItem
        fields = "__all__"


class PlayerGoodsItemSerializer(serializers.ModelSerializer):
    goods_item = GoodsItemSerializer()
    class Meta:
        model = PlayerGoodsItem
        fields = "__all__"

返回数据:

{
	"id": 7,
	"goods_item": {
		"id": 1,
		"create": "2019-12-03T14:02:12+08:00",
		"update": "2019-12-03T14:04:21.868583+08:00",
		"sub_goods_type": 1,
	},
	"create": "2019-12-03T14:14:34.934473+08:00",
	"update": "2019-12-03T14:14:35.052401+08:00",
}
分享文章:

猜你喜欢:

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注