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 %} 

现在我试图显示模板中的一个类别中的所有可用产品的类别中的可用产品的列表(即在面板主体中)。我如何改变视图来访问这些反向关系?对于基于类的视图来说相当新颖。

回答

2

您可以使用相关领域的经理products_set,如访问相关产品为每个类别:

{{category.category_name}} //trying to change here by displaying all model_names!! 
<ul> 
{% for product in category.product_set.all %} 
    <li>{{ product.model_name }}</li> 
{% endfor %} 
</ul> 

如果您需要更复杂的过滤,你想要么在您的视图或写做自定义模板标签。在视图中做它会是这个样子:

class CategoryList(ListView): 
    model = Category 
    template_name = 'categories.html' 

    def get_queryset(self): 
     qs = super(CategoryList, self).get_queryset() 
     for category in qs: 
      category.some_filtered_products = category.product_set.filter(...) 
     return qs 

,将解决该视图中的查询集,并把过滤后的产品进入一个新的内存属性上的每个Category实例。

+0

哇!不知道我们可以直接在模板中使用它!谢谢 – Abhishek 2015-03-02 20:49:54

+1

是的 - 你不能将参数传递给模板中的方法,但任何可以使用无参数评估的工作都可以正常工作。有关详细信息,请参阅此处的“幕后”框:https://docs.djangoproject.com/en/1.7/topics/templates/#variables – 2015-03-02 21:09:47