简体   繁体   English

Django:ModelSerializer的自定义字段映射

[英]Django: Custom field mapping for ModelSerializer

I'm hosting an API and for that, I'm using Django Rest Framework . 我托管一个API,为此,我使用的是Django Rest Framework I have a Model and I'm getting some data through the API to store in the DB through models & model serializers. 我有一个模型,我正在通过API获取一些数据,以通过模型和模型序列化器存储在数据库中。

My problem is that the column names in the MySQL table are different than the data I'm getting on the API hosted. 我的问题是MySQL表中的列名与我在托管的API上获得的数据不同。 eg: 例如:

Data Got through API: 通过API获得的数据:

{
    "a": "b",
    "c": "d",
    "e": "f",
}

And my Model is as below: 我的模型如下:

class Table(models.Model):
    x  = models.CharField(max_length=25,primary_key=True)
    y  = models.CharField(max_length=25)
    z  = models.CharField(max_length=25)

Serializer: 序列化器:

class TableSerializer(serializers.ModelSerializer):
    class Meta:
        model = Table
        fields = ( 'x', 'y', 'z')

How can I map a -> x , b -> y , c -> z ? 我如何映射a -> xb -> yc -> z

In your TableSerializer class, you can create your mapping manually: 在TableSerializer类中,可以手动创建映射:

class TableSerializer(serializers.ModelSerializer):
    a = models.CharField(source='x', max_length=25, primary_key=True)
    b = models.CharField(source='y', max_length=25)
    c = models.CharField(source='z', max_length=25)

    class Meta:
        model = Table
        fields = ( 'a', 'b', 'c')

When you return a Table instance, the x , y and z properties will be serialized as a , b and c . 当您返回Table实例时, xyz属性将被序列化为abc Similarly, when you get some data through your API, the fields will be mapped the other way around. 同样,当您通过API获取一些数据时,这些字段将以其他方式映射。

You'll get some more info about source in the DRF docs 您将在DRF文档中获得有关source更多信息。

ilse2005's approach works: you can override the create method in your serializer and do the mapping all by yourself but adding the source parameter in your serializer fields, this will let you create, update and return Table instances easily. ilse2005的方法有效:您可以在序列化程序中覆盖create方法,并自己进行映射,但可以在序列化程序字段中添加source参数,这将使您轻松创建,更新和返回Table实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM