Skip to main content
 首页 » 编程设计

python之具有多个引用的 django 列表模型条目

2024年12月31日21傻小

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

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        | 

我正在使用 Django==1.9.2、django_tables2==1.1.6 和 django-filter==0.13.0 PostgreSQL.

问题: 我使用 Song 作为表和过滤器的模型,因此查询集以选择 FROM song 开头。但是,在加入 Play 表时,在“Stairway to Heaven”的情况下我得到了两个条目(我知道,即使是一个也太多了: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 每行显示一个轨道“聚合”来自引用的信息的正确方法?

请您参考如下方法:

我认为正确的方法是使用 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(...))