2011-01-13 90 views
1

我需要製作一個過濾器,它檢查日期範圍的對象。現在我正在執行一個非常低效的循環來檢查所有的對象。我想簡化這個數據庫調用。Django的複雜的查詢

的邏輯是你有一個startend日期對象。我需要檢查開始或結束是否在預約範圍內。

if (start >= appointment.start && start < appointment.end) || 
    (end > appointment.start && end <= appointment.end) 

我可以在SQL做到這一點,但我不熟悉的更復雜的查詢Django的模型結構。

回答

4

您需要&和range現場查找Q型物體或運營商和

Q對象:http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

範圍:http://docs.djangoproject.com/en/dev/ref/models/querysets/#range

Entry.objects.filter(Q(start__range=(appointment.start, appointment.end)) | 
    Q(end__range=(appointment.start, appointment.end))) 

如果SQL BETWEEN,是不是你在尋找什麼,你總是可以使用特定的組合Q對象來精確地再現您的條件:

Entry.objects.filter((Q(start__gte=appointment.start) & Q(start__lt=appointment.end)) | 
    (Q(end__gt=appointment.start) & Q(end__lte=appointment.end))) 
+0

使用的第一個例子,你用`start_date`和`end_date`在哪裏? – 2011-01-13 19:54:37