Awesome! I thought there would to be a way to use .values().distinct()
without tons of subsequent queries.

I actually just posted the core of my model -- there are several more
related classes, but this covers the basic idea. As a result, I might
be back looking for clarification on that keyword method, but I think
I'll see how far I get with what I have for now...

Many thanks,
Andy

On Nov 1, 8:29 pm, Malcolm Tredinnick <[EMAIL PROTECTED]>
wrote:
> On Thu, 2007-11-01 at 11:35 -0700, Andy Brody wrote:
> > Ah, thanks for the values() hint. It seems to work decently. I don't
> > really need to access related model fields, I just want a list of
> > unique group objects associated with a given musician's activities.
>
> > The above becomes instead:
>
> > qset = theMusician.activity_set.all().values('group').distinct()
> > # returns list of {'group': id} without duplicates
>
> > grouplist = [Group.objects.get(id=valuesdict['group']) for valuesdict
> > in qset]
>
> If efficiency was a concern, this does a lot of queries (len(qset) of
> them). Instead, try
>
>         grouplist = Group.objects.filter(id__in=[(d['group'] for d in
>         qset])
>
> which constructs grouplist with only one extra query.
>
> > Or maybe it would be better to leave the duplicates testing in python:
>
> > grouplist = [act.group for act in theMusician.activity_set.all()]
> > group_ids = []
> > for group in grouplist[:]:
> >     if group.id in group_ids:
> >         grouplist.remove(group)
> >     else:
> >         group_ids.append(group.id)
>
> > Why doesn't set(grouplist) remove the duplicates, anyway?
>
> Because the instances aren't the same even when the id values are the
> same. get() returns a *new* instance each time.
>
> > Do these both make sense? Would one hit the database less than the
> > other?
>
> My modified solution is probably fastest for what you can do at the
> moment without custom SQL. Two SQL queries and one list comprehension in
> Python.
>
> Regards,
> Malcolm
>
> --
> What if there were no hypothetical questions?http://www.pointy-stick.com/blog/


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to