我要第一個!歌曲來自 NL 或 BE 的藝術家。目前我正在向所有藝術家查詢一首歌。這是我的查詢。
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()
但我不知道如何在查詢過濾器中執行此操作。有任何想法嗎?提前致謝。
uj5u.com熱心網友回復:
據我正確理解這個問題,您希望每首歌都有第一位藝術家,因為一首歌可以有多個藝術家。我的解決方案可能不是最好的,因為它只是回傳物件的值,但也許有幫助。
Song.objects.filter(artists__country__code__in=['NL', 'BE']).values("uuid", "name", "artists__name", "artists_uuid")
這將回傳具有定義值的字典查詢集。
uj5u.com熱心網友回復:
您要做的是獲得國家代碼 ['NL', 'BE'] 的第一位藝術家
使用這樣的東西
Song.objects.filter(artists__country__code__in=['NL', 'BE']).first().artists.first()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/338295.html
