嗨,我是使用 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] 删除。
我来说两句