Search code examples
pythondjangodjango-rest-frameworkdjango-serializer

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...


Solution

  • 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.