Sql django,按查询组合两个组

Sql django,按查询组合两个组,sql,django,django-queryset,Sql,Django,Django Queryset,我有以下型号 class Accept(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(db_index=True) invitation = generic.GenericForeignKey('content_type', 'object_id') class OfferBase(models.Model):

我有以下型号

class Accept(models.Model):

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField(db_index=True)
    invitation = generic.GenericForeignKey('content_type', 'object_id')


class OfferBase(models.Model):

    user = models.ForeignKey(settings.AUTH_USER_MODEL)

    accepts = generic.GenericRelation(Accept)

    class Meta:
        abstract = True


class FooOffer(OfferBase):

    # pass


class BarOffer(OfferBase):

    # pass
我想计算按“接受”排序的用户分组的接受数

在django

FooOffer.object.values('user', 'user__username'
).annotate(num_accepts=Count('accepts__id')).order_by('-num_accepts')
在sql中

SELECT "foo_offer"."user_id", "user"."username", COUNT("accept"."id") AS "num_accepts" FROM "foo_offer" INNER JOIN "user" ON ( "foo_offer"."user_id" = "user"."id" ) LEFT OUTER JOIN "accept" ON ( "foo_offer"."id" = "accept"."object_id" AND ("accept"."content_type_id" = 20\
2) ) GROUP BY "foo_offer"."user_id", "user"."username" ORDER BY "num_accepts" DESC


BarOffer.object.values('user', 'user__username'
).annotate(num_accepts=Count('accepts__id')).order_by('-num_accepts')
我想合并两个查询的结果(Foo和Bar) 我不知道如何用sql编写,我想我需要
union
sum
在django我该怎么做?
也许用ORM不可能做到这一点,那么在django世界中,没有ORM我怎么做查询呢

结果行将具有以下列

user_id         username                sum( count(accept.id) )

嗯,我不确定这一点,但我不认为你可以把它们结合起来,因为它们是两个不同模型上的查询集。即使您让它们从一个模型继承,但该模型是抽象的,不支持查询。能否显示表foo_offer、表user和表accept的结构?我认为您可以先将accept作为子查询进行计数,然后将3个表连接在一起,但这可能不是您想要的,我们需要更多关于这个问题的信息。我已经在op中包含了FooOffer,Accept模型定义。为了简单起见,User只是一个带有
username
的模型