Django 中的 orm 查询

史蒂文·丹尼尔·安德森

嗨,我是使用 django 的新手,我不知道如何进行良好的查询。这是我的模型:

class Product(models.Model):
    client = models.ForeignKey('Client')
    subcategory = models.ForeignKey('SubCategory')
    product = models.CharField(max_length=30)
    description = models.CharField(max_length=100)
    created_date = models.DateTimeField(default=timezone.now)
    def __str__(self):
            return self.product

我的观点是:这是我的观点

def index(request):
    category = Category.objects.all()
    products = Product.objects.all()
    return render(request,'ganagroapp/index.html', {'category' : category, 'products' : products} )

和我的模板

           <section >
                {% for product in products %}
                <div class="product">
                <p> {{ product }} </p>
                </div>
                {% endfor %}
            </section>

当我输入 Product.object.all() 时,我只是作为输出字段产品接收,我需要作为输出产品、描述、客户端。

类似于 mysql 的输出

select * from Products
格莱美

我假设你正在做这样的事情:

products = Product.objects.all()
for p in products:
    print(p)

这将打印产品的名称,因为您已经覆盖了该__str__方法。

如果删除此方法,您将看到它实际上是包含您在Products类中定义的所有属性的对象列表

要打印您指定的值:

print(p.product, p.description, p.client)

上面的例子正是你的模板中发生的事情:

<section >
     {% for product in products %}
     <div class="product">
     <p> {{ product.product }}
         {{ product.description }} 
         {{ product.client }}</p>
     </div>
     {% endfor %}
 </section>

您只是渲染product将解决任何__str__返回对象直接访问属性。

您在模板中访问的数据是幕后实际的 Python 对象。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章