开发者

Elegant way to count frequency and correlation of many-to-many relationships with Django ORM?

开发者 https://www.devze.com 2023-01-10 20:34 出处:网络
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 e开发者_Go百科xtract:

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 e开发者_Go百科xtract:

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

Thanks


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消