Juan-Kabbali
Juan-Kabbali

Reputation: 2454

Serialize ID and URL at the same time Django Rest Framework

I'm starting with DRF and i would like to serialize both ID and Hyperlinked URL at the same time.

Let me define a simple example model:

class Account(model.Models):
    name = models.CharField(max_length=100)
    active = models.BooleanField()

I know that there is a ModelSerializer which represents the object as follows:

{
   "id": 1,
   "name": "library",
   "active": true
}

And there is as well an HyperlinkedModelSerializer which represents the object as follows:

{
   "url": "http://127.0.0.1:8000/core/accounts/1/",
   "name": "library",
   "active": true
}

Intrinsically in the HyperlinkedModelSerializer we can retrieve the row's ID, but what I'm looking for is to get something like this:

{
   "id": 1,
   "url": "http://127.0.0.1:8000/core/accounts/1/",
   "name": "library",
   "active": true
}

Upvotes: 0

Views: 994

Answers (3)

You should add this to the Nginx config file:

location /api/ {
        .
        .
        .
        proxy_set_header X-Forwarded-Proto https;
        .
        .
        .
    }

Upvotes: 0

Juan-Kabbali
Juan-Kabbali

Reputation: 2454

I got the answer from here it works well for me.

Doing this you can avoid to define model's fields and after that define them again in the serializer with the id and url fields like ['url', 'id', 'name', 'active']

With the example it seems dummy but this can save you a lot of time when you deal with models which have much more fields ...

class AccountSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Account
        fields = [field.name for field in model._meta.fields]
        fields.extend(['id', 'url'])

Upvotes: 2

Nico Griffioen
Nico Griffioen

Reputation: 5405

I checked the docs, you can explicitly add the field 'id' by including it in fields.

class AccountSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Account
        fields = ['url', 'id', 'name', 'active']

Upvotes: 2

Related Questions