简体   繁体   中英

Django: Custom field mapping for ModelSerializer

I'm hosting an API and for that, I'm using 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.

My problem is that the column names in the MySQL table are different than the data I'm getting on the API hosted. eg:

Data Got through 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 ?

In your TableSerializer class, you can create your mapping manually:

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 . Similarly, when you get some data through your API, the fields will be mapped the other way around.

You'll get some more info about source in the DRF docs

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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