我正在尝试使用反向外键关系来获取遍历2个模型的对象。我已经能够获取第一个模型(ipv4address)的对象,但是无法通过反向外键获取链接到该对象的对象。 我对django来说相当新,所以我可能会接近这个错误。任何建议都更受欢迎。
我将所有对等对象传递给模板:
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))
型号:
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()
模板:
{% 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 %}
答案 0 :(得分:1)
实际上按设计工作......问题在于(缺少)数据库内容。