django access to parent
Posted
by SledgehammerPL
on Stack Overflow
See other posts from Stack Overflow
or by SledgehammerPL
Published on 2010-06-09T10:14:42Z
Indexed on
2010/06/09
11:22 UTC
Read the original article
Hit count: 220
model:
class Product(models.Model):
name = models.CharField(max_length = 128)
(...)
def __unicode__(self):
return self.name
class Receipt(models.Model):
name = models.CharField(max_length=128)
(...)
components = models.ManyToManyField(Product, through='ReceiptComponent')
def __unicode__(self):
return self.name
class ReceiptComponent(models.Model):
product = models.ForeignKey(Product)
receipt = models.ForeignKey(Receipt)
quantity = models.FloatField(max_length=9)
unit = models.ForeignKey(Unit)
def __unicode__(self):
return unicode(self.quantity!=0 and self.quantity or '') + ' ' + unicode(self.unit) + ' ' + self.product.genitive
And now I'd like to get list of the most often useable products:
ReceiptComponent.objects.values('product').annotate(Count('product')).order_by('-product__count'
the example result:
[{'product': 3, 'product__count': 5}, {'product': 6, 'product__count': 4}, {'product': 5, 'product__count': 3}, {'product': 7, 'product__count': 2}, {'product': 1, 'product__count': 2}, {'product': 11, 'product__count': 1}, {'product': 8, 'product__count': 1}, {'product': 4, 'product__count': 1}, {'product': 9, 'product__count': 1}]
It's almost what I need. But I'd prefer having Product object not product value, because I'd like to use this in views.py for generating list.
© Stack Overflow or respective owner