带有多个引用的Django列表模型条目

时间:2018-10-30 13:39:35

标签: python django django-tables2 django-filters

我有以下表示歌曲和每首歌的演奏的模型:

from django.db import models


class Play(models.Model):
     play_day = models.PositiveIntegerField()
     source = models.CharField(
         'source',
         choices=(('radio', 'Radio'),('streaming', 'Streaming'), )
     )
     song = models.ForeignKey(Song, verbose_name='song')    


class Song(models.Model):

     name = models.CharField('Name')

图片我有以下条目:

歌曲:

|ID | name                |
|---|---------------------|
| 1 | Stairway to Heaven  |
| 2 | Riders on the Storm |

播放:

|ID | play_day | source    | song_id |
|---|----------|-----------|---------|
| 1 | 2081030  | radio     | 1       |
| 1 | 2081030  | streaming | 1       |
| 2 | 2081030  | streaming | 2       |

我想列出所有曲目,如下所示:

| Name                | Day        | Sources          |
|---------------------|------------|------------------|
| Stairway to Heaven  | 2018-10-30 | Radio, Streaming |
| Riders on the Storm | 2018-10-30 | Streaming        |

我在PostgreSQL中使用Django==1.9.2django_tables2==1.1.6django-filter==0.13.0

问题: 我使用Song作为表和过滤器的模型,因此查询集从选择FROM song开始。但是,在加入Play桌时,在“通往天堂的阶梯”的情况下,我会得到两个条目(我知道,甚至一个都太多了:https://www.youtube.com/watch?v=RD1KqbDdmuE)。

我尝试过的事情:

  • 我尝试在Song上插入一个与众不同的词,尽管这样会产生一个问题,即我无法对Song.id以外的其他列进行排序(假设我在该列上确实与众不同)

  • 聚合:这将产生最终状态,实际上是一个字典,并且不能与django_tables一起使用。

  • 我发现了针对PostgreSQL Selecting rows ordered by some column and distinct on another的解决方案,尽管我不知道如何使用django做到这一点。

问题: 使用Django的ORM,每行显示一条“聚集”来自引用的信息信息的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

我认为正确的方法是使用array_agg postgresql函数(http://postgresql.org/docs/9.5/static/functions-aggregate.htmlhttp://lorenstewart.me/2017/12/03/postgresqls-array_agg-function)。

Django似乎实际上支持此功能(至少在2.1版中:http://docs.djangoproject.com/en/2.1/ref/contrib/postgres/aggregates/),因此这似乎是可行的方法。

很遗憾,我现在没有时间对其进行测试,因此我无法提供详尽的答案;但是,请尝试以下操作:Song.objects.all().annotate(ArrayAgg(...))