1

我有一个三个表,一个主要(事务)和两个依赖(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()

我想在这三个表上创建一个具有复杂聚合的查询,并产生具有这种结构的哈希(或查询集):

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

其中 count_of_new_messages 是聚合字段,计算为

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 上实现的(没有 raw)?

4

0 回答 0