【问题标题】:django queryet to print product and it's modelsdjango queryset 打印产品及其模型
【发布时间】:2014-02-18 05:55:03
【问题描述】:

我的模型是

   class Product(models.Model):

         name = models.CharField(max_length=50)
         desc = models.CharField(max_length=50)

         def __unicode__(self):
                 return self.name

   class ProductModels(models.Model):
          product = models.ForeignKey(Product)
          name = models.CharField(max_length=50)
          price = IntegerField(max_length=50)

          def __unicode__(self):
                 return self.name

我可以轻松地在 python 、 product 和它的相关模型中打印,但是在 django 模板中,我无法弄清楚如何打印它们。

我希望在这样的 html 页面中看到数据:

    product1    modelpm1
                modelpm2

    product2    modelpm3
                modelpm4
                modelpm5
                          and so on .....

当然,我已经正确创建了表格和所有与 html 相关的标签,但我无法弄清楚如何在模板中以这种方式打印。

【问题讨论】:

    标签: python django django-templates django-queryset


    【解决方案1】:

    在模板中也是一样的:

    <ul>
    {% for product in objects %}
        <li>{{ product }}
            <ul>
        {% for product_model in product.productmodel_set.all %}
           <li>{{ product_model }}</li>
        {% endfor %}
        </ul></li>
    {% endfor %}
    </ul>
    

    使用以下视图:

    def product_list(request):
       return render(request, 'template.html', {'objects': Product.objects.all()})
    

    或者,如果您愿意,可以使用通用视图:

    class ProductList(ListView):
        template = 'template.html'
        queryset = Product.objects.all()
    

    【讨论】:

      猜你喜欢
      • 2011-12-28
      • 1970-01-01
      • 2011-05-26
      • 2014-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      相关资源
      最近更新 更多