2010-02-18 48 views
0

我試圖簡單地按名稱訪問模板中的多對多模型的值和名稱。有人能告訴我我做錯了什麼嗎?Django模板 - 按名稱訪問M2M屬性和值

我有一個叫做IP的模型。這個模型可以有幾個屬性。我想調用某個特定屬性的「值」。

例如: 我有一個名爲Foo的IP塊。 Foo有一個屬性「bar」,其值爲「祝你好運」。

如何引用M2M中的命名屬性,以及它是否來自模板?

This Works but YUCK !!

{% for attr in ip.attributes.all %} 
    {% ifequal attr.attribute.name 'vendor' %} 
    <td>{{ attr.value }}</td> 
    {% endifequal %}   
{% endfor %} 

非常感謝!

我有一個與此類似的models.py。

models.py 

VALID_IP_TYPES = (("hard", "Hard IP"), 
        ("soft", "Soft IP"), 
        ("verif", "Verification IP")) 

class AttributeType(models.Model): 
    name = models.CharField(max_length = 32, primary_key = True) 
    ip_type = models.CharField(max_length = 16, choices = \ 
        tuple(list(VALID_IP_TYPES) + [("all", "All IP")])) 

    def __unicode__(self): 
     return u'%s' % (self.name) 

class Attribute(models.Model): 
    attribute = models.ForeignKey(AttributeType) 
    value = models.CharField(max_length = 255) 

    def __unicode__(self): 
     return u'%s : %s' % (self.attribute, self.value) 

class IP(models.Model): 
    ip_type = models.CharField(max_length = 16, choices = \ 
          tuple(list(VALID_IP_TYPES), 
          help_text = "Type of IP") 
    name = models.CharField(max_length = 32, help_text = "Generic Name") 
    attributes = models.ManyToManyField(Attribute) 

    def __unicode__(self): 
     return u'%s' % (self.name) 

相關views.py

def search(request): 

    context = RequestContext(request) 

    if not request.POST: 
     form = { 'form' : IPSearch() } 
     return render_to_response('ip_catalog/search.html', form, 
            context_instance = context) 
    else: 
     form = IPSearch(request.POST) 
     if form.is_valid(): 
      response_dict = {} 
      cd = form.cleaned_data 
      ips = ips.filter(**cd)     
      response_dict.update({'ips':ips}) 
      response_dict.update({'success': True }) 
      return render_to_response('ip_catalog/results.html', response_dict, 
           context_instance = context) 

最後的模板片段,我掙扎..

{% for ip in ips %} 
<tr> 
    <td>{{ ip.name }}</td> 
    <td>{{ ip.release_id }}</td> 
    <td>{{ ip.release_date }}</td> 

    <!-- THIS WORKS BUT THERE MUST BE A BETTER WAY! --> 
    {% for attr in ip.attributes.all %} 
     {% ifequal attr.attribute.name 'vendor' %} 
     <td>{{ attr.value }}</td> 
     {% endifequal %}   
    {% endfor %} 

    <!-- THIS DOESN'T WORK! --> 
    <td>{{ ip.attributes.node.value }}</td> 
    <!-- OR THIS! --> 
    <td>{{ ip.attribute_id.foundry }}</td> 
    <!-- OR THIS.. ! --> 
    <td>{{ ip.attribute.process }}</td> 
</tr> 
{% endfor %} 
+0

可能重複http://stackoverflow.com/questions/223990/how-do-i-perform-query-filtering-in- Django的模板) – lqez

回答

0

的經理訪問模型中的結果ManyToManyField,你可以使用.filter()等等。由於其中大多數需要至少一個參數,因此您無法在模板中調用它們。改爲創建一個模板標籤。

0

你不能在模板中做到這一點。這受到Django設計理念的限制。 要做到這一點的唯一方法是在get_vendor等模型中編寫自定義模板標記或幫助函數。

結帳How do I perform query filtering in django templates

的[我如何在Django模板進行查詢過濾(