与Django的联合子查询不同

时间:2019-06-01 08:51:19

标签: django orm distinct-on

我用SQL编写查询,但不知道如何将查询转换为Django ORM:

SELECT DISTINCT ON ("id")
    "id", 
    "name", 
    "national_code", 
    "phone_number", 
    "weight" 
FROM ( ( 
 SELECT "customer"."id", 
    "customer"."name", 
    "customer"."national_code", 
    "customer"."phone_number", 
    1 AS "weight" 
FROM   "customer" 
WHERE  ("customer"."national_code" = '0012923409')) 
UNION ( 
    SELECT "customer"."id", 
        "customer"."name", 
        "customer"."national_code", 
        "customer"."phone_number", 
        3 AS "weight" 
    FROM   "customer" 
    WHERE  ("customer"."name"::text LIKE '%test%')) 
UNION ( 
    SELECT "customer"."id", 
           "customer"."name", 
           "customer"."national_code", 
           "customer"."phone_number", 
           2 AS "weight" 
    FROM   "customer" 
    WHERE  (customer"."phone_number" = '09352167214'))
) AS sub
ORDER BY "id", 5 ASC limit 20

我尝试以下代码:

customer_fields = {'id', 'name', 'national_code', 'phone_number'}

q_by_national_code = self.only(*customer_fields) \
    .filter(national_code__exact="0012923409")\
    .annotate(weight=Value(1, output_field=IntegerField()))

q_by_phone = self.only(*customer_fields) \
    .filter(phone_number__exact='09352167214') \
    .annotate(weight=Value(2, output_field=IntegerField()))

q_by_name = self.only(*customer_fields) \
    .filter(name__contains="test") \
    .annotate(weight=Value(3, output_field=IntegerField()))

final_query = q_by_national_code.union(q_by_name, q_by_phone)

但是当我在final_query上使用独特的功能时,最终查询中没有独特的查询。我的联合查询可能有基于ID提交的重复行,并且由于我向每个联合查询添加了权重字段,因此UNION不会删除重复行。

0 个答案:

没有答案