【问题标题】:Filter query on first many-to-many item过滤第一个多对多项目的查询
【发布时间】:2021-10-27 07:30:11
【问题描述】:

我想要第一个!这首歌的艺术家来自荷兰或比利时。目前我正在向所有艺术家查询一首歌。这是我的查询。

Song.objects.filter(artists__country__code__in=['NL', 'BE'])

这些是我的模型:

class Song(Timestamps):
    uuid = models.UUIDField('UUID', unique=True)
    name = models.CharField('Name', max_length=255, blank=True)
    artists = models.ManyToManyField(Artist)
    ...

class Artist(Timestamps):
    uuid = models.UUIDField('UUID', unique=True)
    name = models.CharField('Name', max_length=255, blank=True)
    country = CountryField(blank=True, null=True)
    ...

我知道我可以像这样访问多对多字段的第一项:

song.artists.first()

但我不知道如何在查询过滤器中执行此操作。 有任何想法吗? 提前致谢。

【问题讨论】:

    标签: django django-queryset


    【解决方案1】:

    据我正确理解问题,您希望每首歌曲都有第一位艺术家,因为一首歌曲可以有多个艺术家。我的解决方案可能不是最好的,因为它只返回对象的值,但也许有帮助。

    Song.objects.filter(artists__country__code__in=['NL', 'BE']).values("uuid", "name", "artists__name", "artists_uuid")
    

    这将返回具有定义值的字典查询集。

    【讨论】:

      【解决方案2】:

      您要做的是获得国家代码 ['NL', 'BE'] 的第一位艺术家

      使用类似的东西

      Song.objects.filter(artists__country__code__in=['NL', 'BE']).first().artists.first()
      

      【讨论】:

        【解决方案3】:

        您似乎想要与属于指定国家/地区的歌曲关联的第一位艺术家。我认为您可以查询Artist 模型本身并指定关联的歌曲。

        Artist.objects.filter(country__code__in=['NL', 'BE'], song__name='My song').first()
        

        【讨论】:

          猜你喜欢
          • 2011-11-07
          • 2011-06-10
          • 2017-08-20
          • 2013-08-23
          • 2015-02-17
          • 1970-01-01
          • 1970-01-01
          • 2014-12-19
          • 1970-01-01
          相关资源
          最近更新 更多