我正在尝试创建一个匹配模型对象的查询集,这是我尝试的:
a = Product.objects.first() # Select first product as a test
b = a.compareproducts_set.all() # Filter only related product "a" in the query
models.py
class Product(models.Model):
category_name = models.ForeignKey(Category, on_delete=models.CASCADE, null = True, blank = True )
name = models.CharField(max_length = 50, null = True, blank = True, unique=True)
class CompareProducts(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
views.py
def home(request):
products = Product.objects.all()
list1 = Product.objects.first()
list2 = CompareProducts.objects.filter(product_id=list1.id)
context = {
'products': products, 'list1': list1, 'list2': list2
}
return render(request,'products/index.html', context)
现在我只有第一个产品"a"它是过滤的相关查询集,如何迭代其他产品以及它们从第二个模型中过滤的查询集?所以我可以有两个列表我可以压缩并在模板
中循环它们解决方案:
在Django模板中我使用:
{% for product in products %}
{{product.name}}<br>
{% for offer in product.compare_products.all %}
{{offer.product}} @ {{ offer.pharmacy.name }} for {{ offer.price}}<br>
{% endfor %}
{% endfor %}
我添加了related_name " comparare_products& quot;标记到我的Compareproducts模型,在我的views.py中,我所要过滤的是:products = Product.objects.all()
products = Product.objects.filter(blah blah blah ).prefech_related('compareproducts_set')
将根据过滤器为您提供产品,并将与每个产品有关系的所有比较产品在单个命中到DB。然后使用比较产品相关的每个产品做smt像:
for p in products:
p.compareproducts_set.all()
完整的文档在这里,请阅读:https://docs.djangoproject.com/en/4.0/ref/models/querysets/prefetch-related
如果您在fk字段中添加related_name
以更好地访问反向关系,则
也将很好:https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.ForeignKey.related_name
class Product(models.Model):
category_name = models.ForeignKey(Category, on_delete=models.CASCADE, null = True, blank = True)
name = models.CharField(max_length = 50, null = True, blank = True, unique=True)
class CompareProducts(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, related_name="campare_products") # add here
然后
products = Product.objects.filter(blah blah blah ).prefech_related('compare_products') # change here
for p in products:
p.compare_products.all() # change here
p。S:我带着手机,也许我的回答有拼写错误,所以请按照文档来做,而不是用我的代码:)