简体   繁体   中英

Django Rest Framework how to serialize a relational Model?

I am learning Django Rest Framework and creating some APIs with success. Now I am trying to serialize a relation, but I don't know how this works. Here is my code:

class Countries(models.Model):
    country = models.CharField(max_length=255)

    class Meta:
        managed = False
        db_table = 'countries'

class Users(models.Model):
    name = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    country = models.ForeignKey(Countries, models.DO_NOTHING)
    date = models.DateTimeField()

    class Meta:
        managed = False
        db_table = 'users' 

In views.py

def get(self,request):
        print(UsersSerializer)
        users = Users.objects.all()
        serializer = UsersSerializer(users,many = True)
        return Response(serializer.data)

Serializer:

class UsersSerializer(serializers.ModelSerializer):
    class Meta:
        model = Users
        fields = '__all__'

When I run the API I am getting

[
  {
    "id": 3,
    "name": "dsadasd",
    "email": "dasd@gmail.com",
    "date": "2020-05-12T12:15:24Z",
    "country": 1
  }
]

In the country field I am getting country id and I was expecting the country name here...

you need to change your UsersSerializer to return country name insread of id.

class UsersSerializer(serializers.ModelSerializer):
      # add this line

    class Meta:
        model = Users
        fields = '__all__'

      # return country name

Further read SerializerMethodField .

You can use the source field argument to retrieve the country instead of the id :

... or may use dotted notation to traverse attributes, such as EmailField(source='user.email') . When serializing fields with dotted notation, it may be necessary to provide a default value if any object is not present or is empty during attribute traversal.

Therefore your serializer should look like this:

class UsersSerializer(serializers.ModelSerializer):
    country = serializers.CharField(source='country.country', default='')

    class Meta:
        model = Users
        fields = ('id', 'name', 'email', 'date', 'country')
        # You may use fields='__all__' but I find the explicit declaration 
        # more flexible.

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