2017-10-06 38 views
0

我想爲我的一個項目構建一個複雜的(對我來說)查詢。 Django版本是1.11.4,PostgreSQL版本是9.6。Django 1.11.4 Postgresql SELECT ARRAY到django orm

這裏是模型。

class Event(models.Model): 
    ... 
    name = models.CharField(max_length=256) 
    classification = models.ForeignKey("events.Classification", related_name="events", null=True, blank=True) 
    ... 

class Classification(models.Model): 
    ... 
    segment = models.ForeignKey("events.ClassificationSegment", related_name="classifications", blank=True, null=True) 
    ... 

class ClassificationSegment(models.Model): 
    ... 
    name = models.CharField(max_length=256) 
    ... 

我封鎖了某處,無法繼續。

from django.db.models import CharField, Value as V 
from django.db.models.functions import Concat 
from django.contrib.postgres.aggregates import ArrayAgg 
from django.db.models import OuterRef, Subquery 
import events.models 


event_subquery = events.models.Event.objects.filter(classification__segment=OuterRef('pk')) \ 
.annotate(event=Concat(V('{id:'), 'id', V(', name:"'), 'name', V('"}'), output_field=CharField())) 

final_list = events.models.ClassificationSegment.objects.annotate(
event_list=ArrayAgg(Subquery(event_subquery.values('event')[:6]))) 

我有一個原始查詢。這裏是。

final_events = events.models.ClassificationSegment.objects.raw('SELECT "events_classificationsegment"."id", "events_classificationsegment"."name", (SELECT ARRAY(SELECT CONCAT(\'{id:\', CONCAT(U0."id", CONCAT(\',\', \'name:"\', U0."name", \'"}\'))) AS "event" FROM "events_event" U0 INNER JOIN "events_classification" U1 ON (U0."classification_id" = U1."id") WHERE U1."segment_id" = ("events_classificationsegment"."id") LIMIT 6)) AS "event_list" FROM "events_classificationsegment"') 

您可以在截圖中看到結果。我想我是對的。誰能幫我?

enter image description here

感謝。

回答

2

Postgres有從子查詢形成陣列的一個非常好的方式:

SELECT foo.id, ARRAY(SELECT bar FROM baz WHERE foo_id = foo.id) AS bars 
    FROM foo 

到ORM內做到這一點,你可以定義Subquery一個子類:

class Array(Subquery): 
    template = 'ARRAY(%(subquery)s)' 

,並使用此在您的查詢集中:

queryset = ClassificationSegment.objects.annotate(
    event_list=Array(event_subquery.values('event')[:6]) 
)