Multiple nested foreign key relationships in Django
No
I'm trying to get an object that traverses 2 models that have a reverse foreign key relationship. I've been able to get the object of the first model (ipv4address), but not able to get the object linked to it with a reverse foreign key. I'm new to django, so I might get this kind of error at first. Any suggestions are welcome.
I pass all peer objects to the template like this:
def view_ix(request, ix):
peers = Peer.objects.filter(exchange=ix).order_by('asn')
return render_to_response('view_ix.html', {
'peers': peers,
'exchange' : ix,
'exchanges' : exchanges.list(),
}, context_instance = RequestContext(request))
role model:
class Peer(models.Model):
exchange = models.CharField(max_length=50)
organisation = models.CharField(max_length=200)
contact = models.EmailField(max_length=254)
asn = models.IntegerField()
def __unicode__(self):
return unicode(self.asn) + '\t' + unicode(self.organisation)
class IPv4Address(models.Model):
peer = models.ForeignKey(Peer)
ip = models.GenericIPAddressField(protocol='IPv4')
def __unicode__(self):
return unicode(self.peer) + '\t' + unicode(self.ip)
class Router(models.Model):
name = models.CharField(max_length=50)
fqdn = models.CharField(max_length=50)
snmpport = models.IntegerField()
snmpcommunity = models.CharField(max_length=50)
def __unicode__(self):
return unicode(self.name)
class PeerStatus(models.Model):
router = models.ForeignKey(Router)
ipv4address = models.ForeignKey(IPv4Address)
state = models.IntegerField()
template:
{% for peer in peers %}
{% for ipv4 in peer.ipv4address_set.all %}
ipv4: {{ ipv4.ip }}<br>
{% for state in ipv4.peerstatus_set.all %}
state: {{ state.state }}<br>
{% endfor %}
{% endfor %}
{% endfor %}
No
Actually works as designed... The problem is in the (missing) database content.