2016-05-05 19 views
0

Djangoクエリーセットにraw sql句を追加することはできますか? RawSQL句を通常のクエリーセットに使用することをお勧めします。 通常のクエリーセットでなければならず、rawquerysetではなく、djangoの管理者で使用します。私の具体的な場合にはDjangoクエリーセットにraw sql where句を追加します。

and exists (
    select 1 
    from ... 
) 

私は2つのモデルCustomerSubscriptionを持っている:私の特定のケースで

は私が句のadditonal existsを追加します。 Subscriptionには、startとオプションのend日付フィールドがあります。

今日、現在のサブスクリプションを持つすべての顧客とクエリセットを取得したいと考えています。このSQL照会のように:

select * 
from customers_customer c 
where exists (
    select 1 
    from subscriptions_subscription sc 
    where sc.customer_id = c.id 
    and sc.start < current_date 
    and (sc.end is null or sc.end > current_date) 
) 

私はクエリーセットを作成できませんでした。私が到着した 最善のことは、のようなものだった:

cs = Customer.objects.annotate(num_subscriptions=RawSQL(
     ''' 
     select count(sc.id) 
     from subscriptions_customersubscription sc 
     where sc.customer_id = customers_customer.id 
     and sc.start < current_date 
     and (sc.end is null or sc.end > current_date) 
     ''', [] 
    )) 

しかし、このクエリはwhere existsと同様にSQLクエリを実行しません。

+1

?手動でテーブルを結合しようとしていますが、 'Customer.objects.filter(subscriptions__start__lt = current_date)'などの自然にそれを行うことに問題はありましたか? – serg

+0

OK自然結合は機能し、私が持っていたいものを正確に行います...私はちょうどそれを考えなかった... – DanEEStar

答えて

2

は、あなたの質問に答えていない、しかし、あなたはこのように顧客を照会することができます:あなたがあなたのモデルを投稿することができます

from django.db.models import Q 

Customer.objects.filter(
    Q(subscription__start__lt=current_date), 
    Q(subscription__end=None) | Q (subscription__end__gt=current_date) 
).distinct() 
+0

まあ、私は簡単な解決策は考えていませんでした。これは質問に答えることはできませんが、それは私の問題を解決するように:upvote – DanEEStar

関連する問題