开发者

Django aggregation with objects

开发者 https://www.devze.com 2023-01-02 16:12 出处:网络
model: class Product(models.Model): name = models.CharField(max_length = 128) (...) def __unicode__(self):

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}, {'produ开发者_JAVA百科ct': 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.


If I'm not mistaken this has the same behaviour but with objects?

Product.objects.all().annotate(usecount=Count('receipt_set')).order_by('-usecount')
0

精彩评论

暂无评论...
验证码 换一张
取 消