views:

35

answers:

1

Hi

I have a Pizza model and a Topping model, with a many-to-many relationship between the two.

Can you recommend an elegant way to extract:

  1. the popularity (frequency) of each topping
  2. the correlation between toppings (i.e. which sets of toppings are most frequent)

Thanks

A: 

Update: Found a better way using a separate model for the join table. Consider a relationship like this:

class Weapon(models.Model):
    name = models.CharField(...)

class Unit(models.Model):
    weapons = models.ManyToManyField(Weapon, through = 'Units_Weapons')

class Units_Weapons(models.Model):
    unit = models.ForeignKey(Unit)
    weapon = models.ForeignKey(Weapon)

Now you can do this:

from django.db.models import Count
Units_Weapons.objects.values('weapon').annotate(Count('unit'))

Original Answer:

I faced a similar situation before. In my case the models were Unit and Weapon. They had a many to many relationship. I wanted to count the popularity of weapons. This is how I went about it:

class Weapon(models.Model):
    name = models.CharField(...)

class Unit(models.Model):
    weapons = models.ManyToManyField(Weapon)

for weapon in Weapon.objects.all():
    print "%s: %s" % (weapon.name, weapon.unit_set.count())

I think you can do the same for Pizza and Topping. I suspect there might be other (better) ways to do it.

Manoj Govindan