Django查询集过滤和注释

时间:2018-12-08 14:15:04

标签: django django-models

如何在Django查询中写那个?也许在子查询中?有人可以帮忙吗? 我在sql中这样写:

select distinct tt.client_id
from
(select tk.client_id, min(tk.changedon) min_date
from app_tickets_ticket tk
where tk.status_id=7 and tk.active=FALSE
group by tk.client_id) tt, app_tickets_ticket tr
where
tr.client_id=tt.client_id
and tr.status_id in(5,6) and tr.active=FALSE
and tt.min_date::DATE between '2018-01-05'::DATE and '2018-12-09'::DATE
and tr.changedon::DATE<=tt.min_date::DATE
and tt.client_id not in(select tm.client_id from app_tickets_ticket tm
                   where tm.active=FALSE and tm.changedon::DATE between '2018-01-05'::DATE and '2018-12-09'::DATE
                     and tm.changedon<=tt.min_date
                   and tm.status_id in(8,10,11,12,13,14,15,16,17))
union
select distinct tt.client_id from (
select tk.client_id, min(tk.changedon) min_date
from app_tickets_ticket tk
where tk.active=FALSE
group by tk.client_id
) tt, app_tickets_ticket tr
where tt.min_date::DATE between '2018-01-05'::DATE and '2018-12-09'::DATE
and tt.client_id=tr.client_id and tt.min_date=tr.changedon
and tr.status_id=7

TicketStatus模型:

class TicketStatus(models.Model):
     name = models.CharField('Name', max_length=300, blank=False, null=False, default='-')

客户模型:

class Clients(models.Model):
     fio = models.CharField('Fio', max_length=300, blank=False, null=False)

机票型号:

class Ticket(models.Model):
    status = models.ForeignKey(TicketStatus, blank=False, null=False, on_delete=models.PROTECT)
    createdon = models.DateTimeField('DateIn', auto_now=False, auto_now_add=True)
    changedon = models.DateTimeField('DateOut', auto_now=True)
    active = models.BooleanField('Active', default=True, blank=False, null=False)
    client = models.ForeignKey(Clients, verbose_name='Client', related_name='tickets', blank=True, null=True,
                           on_delete=models.PROTECT)

1 个答案:

答案 0 :(得分:0)

不要!

如果您的查询已经过测试和优化,除非您想在学习Django ORM中进行此练习,否则将需要大量工作来重写(并重新优化)它。

您可以在Django中执行SQL,并使用raw通过ID查找对象。您需要对SQL稍加修改,以返回id而不是client_id):

client = Clients.objects.raw("select distinct tt.client_id as id ...")