raddevon
raddevon

Reputation: 3340

Django: How do I count the number of objects related to another in the database?

I want to make an application that will allow people to form groups to buy items together. I need a way to see how many people are already buying. I have the following 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

I know conceptually that I simply need to take the quantity in the offer and subtract the number of buyers, but I don't really know how to accomplish this. Based on what I've read, it seems I may be able to do it with something like this:

def remaining(self):
        return self.objects.aggregate(Count('buyers'))

I'm not very confident, though. Can anyone help me out with the best approach?

Upvotes: 1

Views: 5728

Answers (1)

eruciform
eruciform

Reputation: 7736

You can just get the results and then count them:

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

Actually, to update, the documentation says not do do that, though it would work, so:

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

Upvotes: 1

Related Questions