Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango: How do I count the number of objects related to another in the database?
    primarykey
    data
    text
    <p>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:</p> <pre><code>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 </code></pre> <p>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:</p> <pre><code>def remaining(self): return self.objects.aggregate(Count('buyers')) </code></pre> <p>I'm not very confident, though. Can anyone help me out with the best approach?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload