Rest Framework反序列化一个字段并序列化模型对象 [英] Rest Framework deserialize one field and serialize model object

查看:80
本文介绍了Rest Framework反序列化一个字段并序列化模型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想使用1个字段反序列化.但是,我想根据模型将其序列化为对象.

Hi I want to deserialize only using 1 field. However, I want to serialize it as an object depending on the model.

假设我有:

#models.py
class Product(models.Model):
    name = models.CharField()
    amount = models.IntegerField()
    description = models.TextField()

class Query(models.Model):
    name = models.CharField()
    product = models.ForeignKey(Product)
    ...

#serializers.py
class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

class QuerySerializer(serializers.ModelSerializer):
    product = ProductSerializer()

    class Meta:
        model = Query
        fields = '__all__'

我想在QuerySerializer上发布/反序列化这样的内容:

I want to POST/deserialize something like this on the QuerySerializer:

{
    "name": "Query 1",
    "product": "Banana",
    ...
}

并且我想要这样的东西来换取序列化器:

and I want something like this in return for serializer:

{
    "name": "Query 1",
    "product": {
                   "name": "Banana",
                   "amount": 1,
                   "description": "Banana description"
               }
    ...
}

我知道有一种方法可以覆盖 to_internal_value ,但是我不喜欢它,因为它与ValidationErrrors混为一谈.

I know a way is overriding to_internal_value but I do not like it since it messes up with ValidationErrrors.

我也得到了这个结果:

{'product': {'non_field_errors': 
['Invalid data. Expected a dictionary, but got str.']}}

推荐答案

首先,在 Product name 字段中输入> 唯一 ,以避免不必要的麻烦.

First of all, make the name field of Product as unique to avoid unnecessary complications.

class Product(models.Model):
    name = models.CharField(unique=True)
    amount = models.IntegerField()
    description = models.TextField()

,然后将您的序列化器更改为

and change your serializer as,

class QuerySerializer(serializers.ModelSerializer):
    product = serializers.CharField(write_only=True)

    class Meta:
        model = Query
        fields = '__all__'

    def create(self, validated_data):
        product_name = validated_data.pop('product')
        product_instance = Product.objects.get(name=product_name)
        return Query.objects.create(product=product_instance, **validated_data)

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep['product'] = ProductSerializer(instance.product).data
        return rep

参考: DRF:使用嵌套序列化程序进行简单的外键分配?

这篇关于Rest Framework反序列化一个字段并序列化模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆