django - 在 Django 中使用 through 查询多对多字段

标签 django django-models many-to-many

我在 Django 中有一个类似这样的模型:

class Classification(models.Model):
  name = models.CharField(choices=class_choices)
  ...

class Activity(models.Model):
  name = models.CharField(max_length=300)
  fee = models.ManyToManyField(Classification, through='Fee')
  ...

class Fee(models.Model):
  activity = models.ForeignKey(Activity)
  class = models.ForeignKey(Classification)
  early_fee = models.IntegerField(decimal_places=2, max_digits=10)
  regular_fee = models.IntegerField(decimal_places=2, max_digits=10)

这个想法是将有一组与每个事件和分类对相关联的费用。分类就像学生、教职员工等。

我知道那部分工作正常。

然后在我的应用程序中,我查询一组事件:
activities = Activity.objects.filter(...)

它返回事件列表。我需要在我的模板中显示带有费用的事件列表。像这样的东西:
Activity Name
Student Early Price - $4
Student Regular Price - $5
Staff Early Price - $6
Staff Regular Price - $8

但是我不知道在没有针对每个事件/类对的费用对象的特定获取查询的情况下获取此信息的简单方法。

我希望这会奏效:
activity.fee.all()

但这只是返回分类对象。有没有办法通过我已经查询的事件获取配对的费用对象数据?

还是我这样做完全错误?

最佳答案

考虑到 michuk 将“费用”重命名为“分类”的提示:

事件模型上费用对象的默认名称将是fee_set。因此,为了获得您的价格,请执行以下操作:

for a in Activity.objects.all():
    a.fee_set.all() #gets you all fees for activity

不过有一件事,正如您所看到的,您最终会在每个事件对象上执行 1 次 SELECT 以收取费用,有一些应用程序可以帮助解决这个问题,例如,django-batch-select在这种情况下只执行 2 个查询。

关于django - 在 Django 中使用 through 查询多对多字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2156950/

相关文章:

java - 如何一次删除 Hibernate JoinTable 中的所有关联?

mysql - 如何查询多对多?

python - 没有电子邮件的用户无法使用 Django 的评论框架发表评论

django - 修改 Wagtail 发布下拉列表(每个应用程序)

django - 在 Pycharm 上使用 Python 3.7 给我 : "Error: Django is not importable in this environment"

python - Django:durationField 默认值

python - 在 Django 中按非字段过滤

django - 如何在 django cms 中扩展插件

python - 如何创建具有 M2M 和 FK 关系的 Django 模型的精确副本

mysql - 从多对多关系调用时,Sequelize 以复数形式搜索表