Django 对象聚合
模型:
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
现在我想获取最常用产品的列表:
ReceiptComponent.objects.values('product').annotate(Count('product')).order_by('-product__count'
示例结果:
[{'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}]
这几乎是我所需要的。但我更喜欢产品对象而不是产品值,因为我想在views.py 中使用它来生成列表。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我没记错的话,这有相同的行为,但是对于对象?
If I'm not mistaken this has the same behaviour but with objects?