0

好吧,所以我的脑子要糊涂了……

我有2个模型。一个是卡片位置,另一个是卡片类型。我有一个视图和模板,可以显示特定机箱中的卡。我似乎无法开始工作的是外键参考。我想在模板中显示 CardType.sName。

我确定我刚刚做了一些愚蠢的事情......

模型.py:

class CardLocation(models.Model):
  chassis = models.ForeignKey(Chassis)
  slot = models.CharField(max_length=20)
  slot_sub = models.CharField(max_length=20)
  CardType = models.ForeignKey(CardType)
  PartNum = models.CharField(max_length=200)
  ProdID = models.CharField(max_length=200)
  versID = models.CharField(max_length=200)
  serialNum = models.CharField(max_length=200)
  cleiCode = models.CharField(max_length=200)
  lastSeen = models.DateTimeField()
  isActive = models.BooleanField(default=0)
  def __unicode__(self):
    return self.slot 


class CardType(models.Model):
  sName = models.CharField(max_length=5)
  lName = models.CharField(max_length=200)
  description = models.CharField(max_length=200)
  def __unicode__(self):
    return self.sName

视图.py

class DetailView(generic.ListView):
  model = CardLocation
  template_name = 'chassis/detail.html'
  context_object_name = 'cardLoc'

  def get_queryset(self):
    #chassis_id = get_object_or_404(CardLocation, chassis_id__iexact=self.args[0])
    chassis_id = self.args[0]
    return CardLocation.objects.filter(chassis_id=chassis_id)

  def get_context_data(self, **kwargs):
    # Call the base implementation first to get a context
    context = super(DetailView, self).get_context_data(**kwargs)
    # Add in the
    context['chassisQ'] = Chassis.objects.get(id=self.args[0])
    #context['CardType'] = CardType.objects.order_by()
    return context

详细信息.html

{% load staticfiles %}

<h2>
<table>
<tr><td>Name:</td><td>{{ chassisQ.name }}<td></tr>
<tr><td>Owner:</td><td>{{ chassisQ.owner }}<td></tr>
<tr><td>ip Adress:</td><td>{{ chassisQ.ipAddr }}<td></tr>
<tr><td>Last updated:</td><td>{{ chassisQ.lastSeen }}<td></tr>
</table>
</h2>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

{% if cardLoc %}
<table border=1>
<tr><td>slot</td><td>Type</td><td>Part Number</td><td>Product ID/</td><td>Version ID</td><td>Serial Num</td><td>CLEI code</td></tr>
{% for card in cardLoc %}
<tr>
<td align="right">{{ card.slot }}</td>
<td>Type {{ card.cardtype__set.all.sName }} </td> <!-- DISPLAY sName HERE -->
<td>{{ card.PartNum }}</td>
<td align="right">{{ card.ProdID }}/</td>
<td align="left">{{ card.versID }}</td>
<td>{{ card.serialNum }}</td>
<td>{{ card.cleiCode }}</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>No cards are available...</p>
{% endif %}
4

1 回答 1

1

ACard有很多CardTypes(因为它是 ForeignKey 关系),而不仅仅是一个。你有:

<td>Type {{ card.cardtype__set.all.sName }} </td>

您需要遍历所有CardTypes相关的Card

{% for card in cardLoc %}
...
    {% for cardtype in card.cardtype__set.all %}
        <td>Type {{ cardtype.sName }}</td>
    {% endfor %}
...
{% endfor %}
于 2013-05-21T20:17:32.253 回答