Home > Blockchain >  Filter query on first many-to-many item
Filter query on first many-to-many item

Time:10-27

I would like the first! artist for the song to come from NL or BE. At the moment I'm querying all artists for a song. This is my query.

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

and these are my models:

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)
    ...

I know that I can access the first item of the many-to-many field like this:

song.artists.first()

But I don't know how to do this in the query filter. Any ideas? Thanks in advance.

CodePudding user response:

As far as I understand the question correctly you want the first artist for every song, as one song can have multiple artists. My solution might not be the best, because it just returns the values of the objects, but maybe it helps.

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

This will return a queryset of dictionaries with the defined values.

CodePudding user response:

What you are trying to do is to get first artist of with country code ['NL', 'BE']

Use somethings like this

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