Arnold96
Arnold96

Reputation: 123

How can I make this query in Django?

I have theese fields(test_type, status, begin_time, and_time).The status field has three state(0, 1 or 2). I want to make a queryset where:

(test_type = 'difficult') and 
(if status=1 and begin_time + 2x(end_time - begin_time) < timezone.now()) or
(if status=2 and end_time < timezone.now()) 

then select theese fields. If the status state=0 I dont want to select that field. How can i make this queryset with Django ORM?

Upvotes: 0

Views: 46

Answers (2)

Iain Shelvington
Iain Shelvington

Reputation: 32244

Something like the following should work. You need to create the annotation for "twice_end_time" as Django doesn't support that kind of calculation in filters

Model.objects.annotate(
    twice_end_time=F('begin_time') + 2 * F('end_time') - F('begin_time')
).filter(
    Q(test_type='difficult') &
    Q(status=1, twice_end_time__lt=timezone.now()) |
    Q(status=2, end_time__lt=timezone.now())
)

Upvotes: 0

Vaibhav Singh
Vaibhav Singh

Reputation: 942

You will have to use the Q object in Django,

Model.objects.filter((Q(status=1) & Q(begin_time < computed_value_here)) | (Q(status=2) & Q(end_time < computed_value_here)), test_type='difficult')

Upvotes: 1

Related Questions