Creating a QuerySet where the presence of a row is dependent on other rows in the result

33 views
Skip to first unread message

Dave Cole

unread,
Aug 22, 2014, 3:20:03 AM8/22/14
to django...@googlegroups.com
I have a problem where I need to define a QuerySet where the conditions for including one row depend on evaluating values in one or more other rows in the QuerySet.

Is there a way to manually construct a QuerySet by iterating over rows from another QuerySet and individually adding them to the new QuerySet?

Russell Keith-Magee

unread,
Aug 22, 2014, 7:46:06 PM8/22/14
to Django Users
On Fri, Aug 22, 2014 at 3:20 PM, Dave Cole <davejo...@gmail.com> wrote:
I have a problem where I need to define a QuerySet where the conditions for including one row depend on evaluating values in one or more other rows in the QuerySet.

Is there a way to manually construct a QuerySet by iterating over rows from another QuerySet and individually adding them to the new QuerySet?
 
No. At it's core, QuerySet is a wrapper around a relational database, and a relational database uses relational algebra to do what it does. That isn't an iterative activity. If you can't express membership of a queryset as a set of conditions on a single row (where that single row might involve joins on other tables, including itself).

However, you *can* iterate over the results of a queryset. Get an initial candidate set via filter(), then iterate over the results to generate (either by removing unwanted elements, or selecting and inserting elements) a final result set. The output of this process won't be a queryset, but it will be an iterable, and in many cases that will be enough.

Yours,
Russ Magee %-)
Reply all
Reply to author
Forward
0 new messages