On Apr 12, 11:52 am, David <[email protected]> wrote:
> > Hi Jani
>
> > That was very helpful. Is there a way to include select_related into that
> > query? or do I have to list every single field I would like to return using
> > values()?
>
> > last_deleted = ModificationLog.objects.values('thing__id', '
> > thing__prefix', ' thing __first_name', ' thing__last_name', '
> > thing__company_name', 'thing__creator', ' thing __created_on',
> > 'modifier').annotate(deletion_date=Max('modified_on')).filter(thing__deleted=1).order_by('-deletion_date')[:20]
>
> > This for example works, but I don't have access to User. Thing contains a
> > FK to the User model, but I'm unable to do in the template {{
> > object_list.creator.get_full_name }}
>
> > But I am a lot lot closer than I was before, thank you.
One reason why such queries are hard is that they aren't easy to
express using SQL. The left join is correct from ORM perspective: it
can't know that each entry will have at least one log entry attached.
I am not sure how to tell that to the ORM without doing ugly trick
using sql/query.py internals.
If you happen to be using PostgreSQL and Django 1.4 you could probably
do something like this (using DISTINCT ON support added in 1.4):
> ml_objs = ModificationLog.objects.distinct('thing__id').order_by('thing__id',
> 'modified_on').select_related('thing').
You could then swap the objects around:
> [setattr(ml.thing, 'last_mod', ml) for ml in ml_objs]
> things = [ml.thing for ml in ml_objs]
I am not sure at all the above will work, or that the .distinct() and
order_by() calls are correct for your use case. But DISTINCT ON could
work here...
In general fetching the latest object(s) per related category is a
common operation, and it would be extremely nice if prefetch_related
and/or select_related would support that out of the box. It is a very
commonly repeating pattern: show me the latest mail in each thread,
show me the latest edit for each article, show the highest rating
employee per project and so on. A modification of this theme is "show
me the N latest edits per category" which is pretty hard to do
efficiently using the current ORM APIs.
So, if somebody has ideas how to implement this into prefetch_related/
select_related I am all ears.
- Anssi
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
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.