On Fri, Aug 19, 2016 at 05:02:39AM -0700, bobhaugen wrote: > On Friday, August 19, 2016 at 5:20:45 AM UTC-5, Michal Petrucha wrote: > > > > Could you show us the code of with_user? Maybe it does not return an > > unevaluated queryset? > > > > > def with_user(self): > all_agents = EconomicAgent.objects.all() > ua_ids = [] > for agent in all_agents: > if agent.users.all(): > ua_ids.append(agent.id) > return EconomicAgent.objects.filter(id__in=ua_ids) > > Moving the call to with_user to form.__init__ solved the problem in the > form ModelChoiceField.
Thanks for sharing the code. The problem is that the ``with_user`` method, which was called during import, eagerly evaluates ``EconomicAgent.objects.all()`` right away, and returns a QuerySet filtered by the result of that. So even though the final queryset returned by ``with_user`` is not yet evaluated, the filtering condition in that queryset is already fixed. You could fix this by doing something along the lines of:: def with_user(self): return EconomicAgent.objects.filter(users__isnull=False).distinct() The important difference is that this version of ``with_user`` does not evaluate anything eagerly, but rather sets up the necessary filters to get the correct result set at the time of evaluation of that queryset. Depending on what you do with the queryset further, you might need to change it a little bit to remove the ``distinct()`` call, and use a subquery instead. > These questions remain unanswered, although I intend to do a bunch more > testing: > > 1. How pervasive is this problem? Does it affect template variables like > {{ object.foreign_key_method }} where the foreign_key_method returns a > queryset? > 2. Is this behavior clearly documented anywhere? Honestly, I'm not sure what exactly you're asking here. Your implementation of ``with_user`` was hard-wiring a queryset filter based on the state of the database at the time ``with_user`` was called. The rest is just standard Python behavior – since the method was called during import (in the ModelForm definition), the result of that call was used for the rest of the process' lifetime. Cheers, Michal -- 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+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20160819123802.GJ27882%40koniiiik.org. For more options, visit https://groups.google.com/d/optout.
signature.asc
Description: Digital signature