【问题标题】:How to group results into array based on similar values, Django Model/Serializers如何根据相似的值将结果分组到数组中,Django Model/Serializers
【发布时间】:2019-09-11 21:59:19
【问题描述】:

还有:how to group model data based on same values in django

还有 2:Group serializer results based on value

像上面的其他人一样,我需要以特定方式返回的结果。我想将包含一列相似值的结果组合在一起。

如上所述,我想接受这个:

 album |             title |    singer
-------+-------------------+----------
     1 |  exampleSongTitle |   someone 
     1 |  exampleSongTitle |   sometwo
     2 |  exampleSongTitle | somethree
     2 |  exampleSongTitle |   someone

得到这个

[
  {
    "album": 1,
    "tracks": [
      {
        "title": exampleSongTitle,
        "singer": someone
      },
      {
        "title": exampleSongTitle,
        "singer": sometwo
      }
    ]
  },
  {
    "album": 2,
    "tracks": [
      {
        "title": exampleSongTitle,
        "singer": somethree
      },
      {
        "title": exampleSongTitle,
        "singer": someone
      }
    ]
  }
]

我的模特:

class Songs(models.Model):
    title = models.CharField(db_column='Title', max_length=400, blank=True, null=True)
    album = models.CharField(db_column='Album', max_length=400, blank=True, null=True)
    singer = models.CharField(db_column='Singer', max_length=400, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'Songs'

专辑值将是来自同一专辑的曲目的相同值。

【问题讨论】:

  • 你能分享你的模型吗?
  • 刚刚更新了模型问题
  • 您是否考虑过添加Album 模型和Singer 模型并为这些模型设置外键?它会让这种事情变得更简单

标签: django django-rest-framework


【解决方案1】:

由于表格看起来相当平坦,因此您必须在从数据库中获取结果后进行格式化/分组。您可以使用itertools.groupby 来执行此操作

result = []
for album, songs in itertools.groupby(Song.objects.order_by('album'), lambda s: s.album):
    result.append({
        "album": album,
        "tracks": [{
            "title": song.title,
            "singer": song.singer
        } for song in songs]
    })

【讨论】:

  • 现在我爱上了你???
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多