Reputation: 1003
I need to get some data from the database, do some calculation and show the results in the template.
From my research I saw that I could use django-mathfilters. But I read that it is not recommeded to include business logic in the template. So I researched for alternatives.
It seems that I could use annotate. So I have tried this:
def price_supplier(request):
list = request.GET.get("list")
price_list = SupplierPriceList.objects.filter(id=list).annotate(margin=(F('cod_product.sale_price') - F('price')) / F('cod_product.sale_price')).all()
return render(request, 'painel_fornecedor/comparacao_precos.html', {'price_list': price_list})
I have tested this and got the error "Cannot resolve keyword 'cod_product.sale_price' into field." How is the recommended way to implement this?
Here is the model:
class Product(models.Model):
cod_product= models.IntegerField(primary_key=True)
descripction = models.CharField(max_length=120, blank=True, null=True)
sale_price = models.DecimalField(max_digits=20, decimal_places=10, blank=True, null=True)
class SupplierPriceList(models.Model):
cod_product = models.ForeignKey(Product, on_delete=models.PROTECT, blank=True, null=True)
price = models.DecimalField(max_digits=20, decimal_places=10, blank=True, null=True)
Thanks in advance!
Upvotes: 0
Views: 90
Reputation: 4264
To use a related field you need to use __
instead of .
as a lookup.
def price_supplier(request):
list = request.GET.get("list")
price_list = SupplierPriceList.objects.filter(id=list).annotate(
margin=(F('cod_product__sale_price') - F('price')) / F('cod_product__sale_price')
).all()
return render(request, 'painel_fornecedor/comparacao_precos.html', {'price_list': price_list})
Upvotes: 1