I have two models created in my Django app and am looking for a serialization approach so that the IPs are shown in JSON as a list of strings instead of a list of IPAddress objects.
Desired JSON
[
{
"hostname": "www.example.com",
"ip_addresses": [ "1.1.1.1", "2.2.2.2" ]
}
]
Current JSON
[
{
"hostname": "www.example.com",
"ip_addresses": [
{
"id": 1,
"ip_address": "1.1.1.1"
},
{
"id": 2,
"ip_address": "2.2.2.2"
}
]
]
urls.py
class HostSerializer(serializers.ModelSerializer):
hostname = serializers.CharField(source='name', read_only=True)
class Meta:
model = Host
fields = ['hostname', 'ip_addresses']
depth = 1
models.py
class IPAddress(models.Model):
ip_address = models.GenericIPAddressField()
def __str__(self):
return str(self.ip_address)
class Host(models.Model):
name = models.CharField(max_length=100)
ip_addresses = models.ManyToManyField(IPAddress)
def __str__(self):
return self.name