[Fixed]-Django rest frameworok

1👍

There is one of the solutions:

Create a method (or property) in the Device model called, for example, get_logs_url, that returned url for device logs:

class Device(models.Model):
    ...
    get_logs_url(self):
        # First parameter is the url name, 'device-logs' for example
        return reverse('device-logs', kwargs={'device_id': self.device_id})

Add field logs_url to DeviceSerializer

class DeviceSerializer(serializers.ModelSerializer):
    ...
    logs_url = serializers.CharField(source='get_logs_url', read_only=True)

Then the result would be like this

[
    {
        "device_id": "12345"
        "logs": "/api/logs?device_id=12345"
    }
]

If you want absolute url in result then your serializer should look something like this

class DeviceSerializer(serializers.ModelSerializer):
    logs_url = serializer.SerializerMethodField()

    def get_logs_url(self, device):
        return self.context['request'].build_absolute_uri(device.get_logs_url())

Then the result would be like this

[
    {
        "device_id": "12345"
        "logs": "http://localhost/api/logs?device_id=12345"
    }
]

Leave a comment