Friday, August 22, 2014

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


On Fri, Aug 22, 2014 at 3:20 PM, Dave Cole <davejohncole@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 %-)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAJxq84_rP9eR6YKEWg_R59Zn%2Bv%3D%3Dekh7eRKpO4bq2%3D0K04kBTg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment