django在三个表中复杂聚合

时间:2013-11-03 18:51:54

标签: sql django orm

我有三个表,一个主要(Transaction)和两个依赖(TransactionDialogMessages,TransactionDialogLastAccess)。

class Transaction(models.Model):
    status = models.CharField(max_length = 3, default = 'NEW')
    user1 = models.ForeignKey(User, related_name='user1', blank=True, null=True, on_delete=models.SET_NULL)
    user2 = models.ForeignKey(User, related_name='user2', blank=True, null=True, on_delete=models.SET_NULL)
    some_info = models.DateTextField()

class TransactionDialogMessages(models.Model):
    transaction = models.ForeignKey(Transaction)
    user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
    message = models.TextField()
    create_datetime = models.DateTimeField(auto_now = True)

class TransactionDialogLastAccess(models.Model):
     transaction = models.ForeignKey(Transaction)
     user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
     access_time = models.DateTimeField()

我想在这三个表上创建一个带有复杂agregation的查询,并导致具有这种结构的hash(或queryset):

{'transaction_id', 'status', 'user1', 'user2', 'some_info', 'count_of_new_messages'}

其中count_of_new_messages是agregation字段,计算为

count (TransactionDialogMessages(transaction = transaction_id, user = request.user, create_datetime > TransactionDialogLastAccess(transaction = transaction_id, user = request.user).access_time))

真的吗?

更新

我创建了SQL查询,这符合我的目的: SELECT a.id, a.status, ... , b.COUNT_OF_NEW_MESSAGES FROM transaction a LEFT JOIN (SELECT b.transaction_id, COUNT(b.transaction_id) AS COUNT_OF_NEW_MESSAGES FROM transactiondialogmessages b LEFT JOIN transactiondialoglastaccess c ON b.transaction_id = c.transaction_id WHERE b.create_datetime > c.access_time OR c.access_time IS NULL GROUP BY b.transaction_id ) b ON a.id = b.transaction_id;

但它是如何在django orm上实现的(没有原始的)?

0 个答案:

没有答案