你好,我是Django的新手,还有编程。有人可以解释我如何比较同一模型创建的对象吗?
如果找到多个具有相同参数的对象 - “product1”,我希望我的应用做一些事情,理想情况下会创建一个这样的对象:
型号:
class ProductInShop (models.Model):
product = models.ForeignKey(Product)
shop = models.ForeignKey(Shop)
查看:
def products(request):
all_products = ProductInShop.objects.all
return render_to_response('polls/products.html', {
'all_products': all_products,
})
模板:
{% for asd in all_products %}
<li>{{ asd.product.name }}</li>
<li>{{ asd.shop.name }}</li>
</br>
{% endfor %}
答案 0 :(得分:0)
您可以比较md5
个对象:
答案 1 :(得分:0)
我认为,你可以改变你的结构:
型号:
class Product(models.Model):
... all other fields
shops = models.ManyToManyField(Shop)
查看:
def products(request):
all_products = Product.objects.all()
return render_to_response('polls/products.html', {
'all_products': all_products,
})
模板:
{% for product in all_products %}
<li>{{ product.name }}</li>
{% for shop in product.shops.all() %}
<li>{{ shop.name }}</li>
{% endfor %}
</br>
{% endfor %}
<强>更新强>
根据您的结构,您可以写下以下内容:
查看:
def products(request):
all_products = Product.objects.all()
return render_to_response('polls/products.html', {
'all_products': all_products,
})
模板:
{% for product in all_products %}
<li>{{ product.name }}</li>
{% for productinshop in product.productinshop_set.all %}
<li>{{ productinshop.shop.name }}</li>
{% endfor %}
</br>
{% endfor %}
但这将为数据库生成许多查询。如果您在Product model中创建方法,可能会更好:
def get_shops(self):
return Shop.objects.filter(productinshop__product_id=self.pk)
然后在模板中:
{% for product in all_products %}
<li>{{ product.name }}</li>
{% for shop in product.get_shops %}
<li>{{ shop.name }}</li>
{% endfor %}
</br>
{% endfor %}