Reputation: 70
I have a relation whereby many host
s can belong to one network
(imagine a database cluster in Miami - mysql is the host, mia is the network site name). A hostname could be mysql-1c0a-mia.
serializers.py:
class HostSerializer(serializers.ModelSerializer):
host = serializers.SerializerMethodField()
def get_host(self, obj):
site = models.ForeignKey(Network, related_name='site', on_delete=models.DO_NOTHING)
return '{}-{}-{}'.format(obj.service, obj.instance, site)
class Meta:
model = Host
depth = 1 # to show JOINed stuff from Network
fields = [
'id',
'network',
'service',
'instance',
'ipv4_data',
'host',
]
Network class (from models.py):
class Network(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=63)
site = models.CharField(max_length=3)
domain = models.CharField(max_length=63)
vlan = models.PositiveIntegerField(null=True, validators=[MaxValueValidator(4094)])
ipv4_net = models.GenericIPAddressField(protocol='IPv4', null=True)
ipv4_gateway = models.GenericIPAddressField(protocol='IPv4', null=True)
ipv4_netmask = models.PositiveIntegerField(null=True, validators=[MaxValueValidator(32)])
class Meta:
verbose_name = "Network"
verbose_name_plural = "Networks"
def __str__(self):
return self.name
Host class (from models.py):
class Host(models.Model):
network = models.ForeignKey(Network, on_delete=models.SET_NULL, null=True)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
service = models.CharField(max_length=6)
instance = RandomSlugField(length=4, exclude_upper=True)
ipv4_data = models.GenericIPAddressField(protocol='IPv4', null=True)
class Meta:
verbose_name = "Host"
verbose_name_plural = "Hosts"
def __unicode__(self):
return '%s-%s-net.%s' % (self.name, "placeholder-site-name", self.domain)
What's going on with host
at the very end? I essentially just want to pull in the network's site name - mia.
sample json output:
{
"id": "b2994407-6c02-41fa-816c-745c55269ac8",
"network": {
"id": "fa73846a-cfa5-4d7a-97c2-73c1adf0d9a0",
"name": "stackoverflow",
"site": "mia",
"domain": "core.example.com",
"vlan": 1234,
"ipv4_net": "10.23.45.0",
"ipv4_gateway": "10.23.45.1",
"ipv4_netmask": 24
},
"service": "mysql",
"instance": "1c0a",
"ipv4_data": "10.23.45.34",
"host": "mysql-1c0a-<django.db.models.fields.related.ForeignKey>"
},
Upvotes: 0
Views: 41
Reputation: 8077
You are declaring a new ForeignKey
field inside the serializer class, but you just need to access the related ForeignKey
field value:
def get_host(self, obj):
return '{}-{}-{}'.format(obj.service, obj.instance, obj.network.site)
Upvotes: 1