使用 Django ORM 计算多对多关系的频率和相关性的优雅方法?

发布于 2024-09-13 00:20:40 字数 151 浏览 7 评论 0原文

我有一个 Pizza 模型和一个 Topping 模型,两者之间具有多对多关系。

你能推荐一种优雅的方式来提取:

  1. 每个的流行度(频率) 最高
  2. 之间的相关性 配料(即哪组 配料是最常见的)

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冰之心 2024-09-20 00:20:40

更新:找到了一种更好的方法,为连接表使用单独的模型。考虑这样的关系:

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)

现在你可以这样做:

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

原始答案

我以前遇到过类似的情况。就我而言,模型是 UnitWeapon。他们之间存在多对多的关系。我想统计一下武器的受欢迎程度。这就是我的做法:

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())

我认为您可以对 PizzaTopping 做同样的事情。我怀疑可能还有其他(更好)的方法来做到这一点。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文