我有兩個Django模型Profile和Device,彼此之間有一個ManyToMany的關系,像這樣:
class Profile(models.Model)。
devices = models.ManyToManyField(Device, related_name='profile')
我試圖使用annotate()和Count()來查詢所有擁有1個或更多設備的組態檔,就像這樣:
profiles = Profile.objects.annotate(dev_count=Count('devices').filter(dev_count__gt=1)
這很好,它給了我一個QuerySet,其中包含所有具有一個或多個設備的組態檔(4500 ),正如預期的那樣。
接下來,由于 M2M 關系,我想從之前的查詢集中獲得所有組態檔中所有不同設備的串列。
我下面所有失敗的嘗試都會回傳一個空的查詢集。我已經閱讀了關于values、values_list和annotate的檔案,但我仍然無法弄清楚如何在這里進行正確的查詢。
devices = profiles.values('devices').distinct()
devices = profiles.values_list('devices', flat=True).different()
我也嘗試過一次過完成:
devices = (
Profile.objects.values_list('devices', flat=True)
.annotate(dev_count=Count('devices'))
.filter(dev_count__gt=1)
.distinct()
)
uj5u.com熱心網友回復:
你不能使用.values(),因為該專案同時出現在SELECT子句和GROUP BY子句中,所以你開始提到這個欄位,因此COUNT(devices)將為每個組回傳1。
您可以通過以下方式過濾與這些Profile中的至少一個鏈接的Devices:
profiles = Profile.objects.annotate(
dev_count=Count('devices')
).過濾器(dev_count__gt=1)
devices = Device.objects.filter(profile__in=profiles).distinct()
對于一些SQL方言,通常是MySQL,最好先將profiles的串列具體化,而不是用子查詢來作業,所以:
profiles = Profile.objects.annotate(
dev_count=Count('devices')
).過濾器(dev_count__gt=1)
profiles_list = list(profile)
devices = Device.objects.filter(profile__in=profiles_list).distinct()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/332348.html
標籤:
上一篇:pkg_resources.DistributionNotFound。沒有找到'uvloop>=0.14.0'的發行版,并且是uvicorn所需要的。
下一篇:"在試圖為序列化器AssetSerializer上的欄位devUserId獲取一個值時,出現了KeyError。原始的例外文本是:'devUserId'。
