Django:我如何计算数据库中与另一个相关的对象数量?

时间:2011-06-15 22:30:46

标签: python django django-models

我想制作一个应用程序,允许人们组成团队一起购买物品。我需要一种方法来看看有多少人已经在购买。我有以下models.py:

from django.db import models

class Buyer(models.Model):
    ''' Buyer of the item '''

    first_name = models.CharField(max_length=40)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()

    # Pieces together full name from first and last
    def full_name(self): 
        return "%s %s" % self.first_name, self.last_name

    # String representation of buyer in the format 'firstname lastname (email)'
    def __unicode__(self):
        return "%s (%s)" % self.full_name, self.email

class Item(models.Model):
    '''The item being purchased'''

    name = models.CharField(max_length=50)
    description = models.TextField()
    price = models.DecimalField(max_digits=6, decimal_places=2)
    # The number of items to be split
    quantity = models.IntegerField()
    pub_date = models.DateTimeField('Date Offered')
    # Expiration of the item on offer
    expires = models.DateField()

    # Relates item to buyers
    buyers = models.ManyToManyField(Buyer)

    # Calculates remaining slots
    def remaining(self):
        # How do I do this?

    # String representation of item using item name
    def __unicode__(self):
        return self.name

我从概念上知道我只需要提供报价中的数量并减去买家的数量,但我真的不知道如何做到这一点。根据我所读到的内容,似乎我可以用这样的东西来做:

def remaining(self):
        return self.objects.aggregate(Count('buyers'))
但是,我不是很自信。任何人都可以用最好的方法帮助我吗?

1 个答案:

答案 0 :(得分:1)

您可以获得结果,然后计算它们:

def remaining(self):
  return self.quantity - len( self.buyers.all() )

实际上,为了更新,documentation说没有这样做,虽然它会起作用,所以:

def remaining(self):
  return self.quantity - self.buyers.all().count()