我有以下型号
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
我想计算按#accept
排序的用户分组的#次接受在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) )