【问题标题】:django list model entry with multiple references具有多个引用的 django 列表模型条目
【发布时间】:2018-10-30 13:39:35
【问题描述】:

我有以下模型代表歌曲和每首歌曲的播放:

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.2、django_tables2==1.1.6 和 django-filter==0.13.0。

问题: 我使用 Song 作为表和过滤器的模型,因此查询集以选择 FROM song 开头。但是,当加入 Play 表时,我得到了两个“天国阶梯”的条目(我知道,即使一个也太多了:https://www.youtube.com/watch?v=RD1KqbDdmuE)。

我尝试了什么:

  • 我尝试在 Song 中添加 distinct,但这会产生问题,即我无法对 Song.id 以外的其他列进行排序(假设我对该列执行 distinct)

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

  • 我找到了适用于 PostgreSQL Selecting rows ordered by some column and distinct on another 的这个解决方案,虽然我不知道如何用 django 做到这一点。

问题: 使用 Django 的 ORM 从引用中“聚合”信息的每行显示一条轨道的正确方法是什么?

【问题讨论】:

标签: python django django-tables2 django-filters


【解决方案1】:

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

Django 似乎实际上支持这一点(至少在 v. 2.1 中:http://docs.djangoproject.com/en/2.1/ref/contrib/postgres/aggregates/),因此这似乎是要走的路。

很遗憾,我现在没有时间测试它,所以我无法提供完整的答案;但是尝试类似:Song.objects.all().annotate(ArrayAgg(...))

【讨论】:

    猜你喜欢
    • 2017-08-07
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    相关资源
    最近更新 更多