6
Given the table below
product;company;price
AAAAA;forn1;395.69
BBBBB;forn1;939.45
CCCCC;forn1;480.33
DDDDD;forn1;590.59
EEEEE;forn1;847.69
AAAAA;forn2;227.31
BBBBB;forn2;375.90
CCCCC;forn2;602.18
DDDDD;forn2;615.02
EEEEE;forn2;845.20
AAAAA;forn3;120.00
BBBBB;forn3;379.30
CCCCC;forn3;227.98
DDDDD;forn3;522.33
EEEEE;forn3;193.51
AAAAA;forn4;869.01
BBBBB;forn4;287.48
CCCCC;forn4;405.49
DDDDD;forn4;477.97
EEEEE;forn4;971.85
how to return the lowest price of each product and return the supplier’s name?
I’ve tried to:
from django.db.models import Min
q=Quotation.objects.values('product').annotate(m=Min('price'))
for i in q: print(i)
And he returns
{'product': 'AAAAA', 'm': Decimal('120.00')}
{'product': 'BBBBB', 'm': Decimal('287.48')}
{'product': 'CCCCC', 'm': Decimal('227.98')}
{'product': 'DDDDD', 'm': Decimal('477.97')}
{'product': 'EEEEE', 'm': Decimal('193.51')}
But it does not return the supplier. Hence when I try
q=Quotation.objects.values('product').annotate(m=Min('price')).values_list('product','company','m')
for i in q: print(i)
He returns
('AAAAA', 'forn1', Decimal('395.69'))
('AAAAA', 'forn2', Decimal('227.31'))
('AAAAA', 'forn3', Decimal('120.00'))
('AAAAA', 'forn4', Decimal('869.01'))
('BBBBB', 'forn1', Decimal('939.45'))
('BBBBB', 'forn2', Decimal('375.90'))
('BBBBB', 'forn3', Decimal('379.30'))
('BBBBB', 'forn4', Decimal('287.48'))
('CCCCC', 'forn1', Decimal('480.33'))
('CCCCC', 'forn2', Decimal('602.18'))
('CCCCC', 'forn3', Decimal('227.98'))
('CCCCC', 'forn4', Decimal('405.49'))
('DDDDD', 'forn1', Decimal('590.59'))
('DDDDD', 'forn2', Decimal('615.02'))
('DDDDD', 'forn3', Decimal('522.33'))
('DDDDD', 'forn4', Decimal('477.97'))
('EEEEE', 'forn1', Decimal('847.69'))
('EEEEE', 'forn2', Decimal('845.20'))
('EEEEE', 'forn3', Decimal('193.51'))
('EEEEE', 'forn4', Decimal('971.85'))
And it’s not what I want, I need
{'product': 'AAAAA', 'company': 'forn2' 'm': Decimal('120.00')}
{'product': 'BBBBB', 'company': 'forn1' 'm': Decimal('287.48')}
{'product': 'CCCCC', 'company': 'forn1' 'm': Decimal('227.98')}
{'product': 'DDDDD', 'company': 'forn3' 'm': Decimal('477.97')}
{'product': 'EEEEE', 'company': 'forn4' 'm': Decimal('193.51')}
That is, how I do to return the cheapest product and the name of the supplier?
Have you tried adding company to
values()
?q=Quotation.objects.values('product', 'company'
).annotate(m=Min('price'))`– Paulo
Yes, but then it groups by product and by company. And that’s not what I want.
– Regis Santos
Solution for Django 1.11 or higher
– mgibsonbr