Q:

Django : Writing a query with condition referencing aggregation within same table

I have a table similar to this:
id  name   added     count  flag
---------------------------------
01  abcd1  09.02.13    4    false
02  abcd1  10.02.13    1    true  
03  abcd1  11.02.13    3    false
04  abcd1  12.02.13    4    false

I need to find sum of count for a given name with the following conditions:

For a given name
Flag should be false
Entry should be added after the last flag=true entry for that name

In this case I want sum of count for entries 03 and 04. 
How should I do this in Django? 
EDIT:
I am looking for creating a query like this:
SELECT id from sample
WHERE 
  name = 'abcd1' AND
  added > (SELECT MAX(added) FROM sample WHERE name = 'abcd1' AND flag = TRUE)

EDIT:
Also if there was no entry with flag=true then I need all the entries for that name. 

A:

It's fairly straightforward if you use a little subquery:
select
    name,
    sum(count)
from sample s
where flag = false
and (added > (select max(added)
    from sample
    where name = 'abcd1'
    and flag = true)
    OR
    not exists (
        select *
        from sample
        where name = 'abcd1'
        and flag = true)
    )
and name = 'abcd1'

Note the use of the OR not exists clause to handle the case when there are no entries with flag=true.

