0
Django新手在這裏,所以請裸露與我! :)在django基礎視圖中使用反向關係
我有一個Django模型如下:
class Category(models.Model):
category_name = models.CharField(max_length=250, blank=True, null=True)
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
def __unicode__(self):
return self.category_name
class Product(models.Model):
category = models.ForeignKey(Category)
model_name = models.CharField(max_length=255, blank=True, null=True)
class Meta:
verbose_name = "Product"
verbose_name_plural = "Products"
def __unicode__(self):
return self.model_name
在我的意見,我有一個ListView如下:
class CategoryList(ListView):
model = Category
template_name = 'categories.html'
而且我categories.html如下:
{% extends "base.html" %}
{% block content %}
<div>
<h2>Categories</h2>
{% for category in object_list %}
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="h{{category.id}}">
<h4 class="panel-title">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#{{category.id}}" aria-expanded="true" aria-controls="{{category.id}}">
{{category.category_name}}
</a>
</h4>
</div>
<div id="{{category.id}}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="h{{category.id}}">
<div class="panel-body">
{{category.category_name}} //trying to change here by displaying all model_names!!
</div>
</div>
</div>
</div>
{% endfor %}
{% endblock %}
現在我試圖顯示模板中的一個類別中的所有可用產品的類別中的可用產品的列表(即在面板主體中)。我如何改變視圖來訪問這些反向關係?對於基於類的視圖來說相當新穎。
哇!不知道我們可以直接在模板中使用它!謝謝 – Abhishek 2015-03-02 20:49:54
是的 - 你不能將參數傳遞給模板中的方法,但任何可以使用無參數評估的工作都可以正常工作。有關詳細信息,請參閱此處的「幕後」框:https://docs.djangoproject.com/en/1.7/topics/templates/#variables – 2015-03-02 21:09:47