Query for a ManytoMany Field with Through in Django

不问归期 提交于 2019-12-05 08:09:16

Considering michuk's tip to rename "fee" to "classification":

Default name for Fee objects on Activity model will be fee_set. So in order to get your prices, do this:

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

There's one thing though, as you can see you'll end up doing 1 SELECT on each activity object for fees, there are some apps that can help with that, for example, django-batch-select does only 2 queries in this case.

First of all I think you named your field wrong. This:

fee = models.ManyToManyField(Classification, through='Fee')

should be rather that:

classifications = models.ManyToManyField(Classification, through='Fee')

as ManyToManyField refers to a list of related objects.

In general ManyToManyField, AFAIK, is only a django shortcut to enable easy fetching of all related objects (Classification in your case), with the association table being transparent to the model. What you want is the association table (Fee in your case) not being transparent.

So what I would do is to remove the ManyToManyField field from Activity and simply get all the fees related with the activity. And thenm if you need a Classification for each fee, get the Classification separately.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!