我想在Django应用中计算一些统计信息。
使用此架构,
class Rank(models.Model):
rank_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
class Taxon(models.Model):
taxon_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
rank = models.ForeignKey(Rank)
class Passport(models.Model):
id:
taxa: models.ManyToMany(Taxon, through='TaxonPassport')
class Accession(models.Model):
id:
passports= models.ManyToManyField(Passport, through='AccessionPassport')
我想计算每个taxon_name等级组合的加入量。
这是我要使用的Django查询表达式:
queryset = Taxon.objects.filter(passport__accession__institute=self).distinct('passport__accession').values('name', 'rank__name').annotate(counts=Count('name'))
但是它抛出一个非实现错误: NotImplementedError:annotate()+ distinct(fields)未实现。
为解决此问题,我使用“从选择中选择”进行了rawSql查询:
Select "taxon_id", "taxon_name", "name", COUNT(*) as counts from (
SELECT DISTINCT "vavilov2_integration_accession"."accession_id",
"vavilov2_integration_taxon"."taxon_id" as "taxon_id",
"vavilov2_integration_taxon"."name" as "taxon_name",
"vavilov2_integration_rank"."name"
FROM "vavilov2_integration_taxon"
INNER JOIN "vavilov2_integration_taxonpassport" ON ("vavilov2_integration_taxon"."taxon_id" = "vavilov2_integration_taxonpassport"."taxon_id")
INNER JOIN "vavilov2_integration_passport" ON ("vavilov2_integration_taxonpassport"."passport_id" = "vavilov2_integration_passport"."passport_id")
INNER JOIN "vavilov2_integration_accessionpassport" ON ("vavilov2_integration_passport"."passport_id" = "vavilov2_integration_accessionpassport"."passport_id")
INNER JOIN "vavilov2_integration_accession" ON ("vavilov2_integration_accessionpassport"."accession_id" = "vavilov2_integration_accession"."accession_id")
INNER JOIN "vavilov2_integration_rank" ON ("vavilov2_integration_taxon"."rank_id" = "vavilov2_integration_rank"."rank_id")
WHERE "vavilov2_integration_accession"."institute_id" = 2) as TMP
group BY "taxon_name", "name", "taxon_id" ;
我正在尝试将其转换为Django ORM表达式,但我不知道如何。有什么建议吗?
谢谢。