Я пишу запрос в 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, в окончательном запросе нет отдельного запроса. Мой запрос на объединение может содержать дублирующиеся строки на основе идентификатора, и из-за поля веса, которое я добавлял в каждый запрос объединения, UNION не удаляет повторяющиеся строки.