Saturday, September 11, 2010

Sorting related model

Given the following two models forming the base of a wiki-style app:

class Page(models.Model):
    current_revision = models.IntegerField()

class PageContent(models.Model):
    page = models.ForeignKey(Page)
    revision = models.IntegerField()
    created = models.DateTimeField()

Here, we have a canonical Page object with a current_revision that always points to the most current revision, stored in PageContent.  How can I construct a Page queryset, ordered by the Pages that have the most recently-created PageContent?

Currently, what I am doing is:

qs = PageContent.objects.filter(revision=F('page__current_revision')).order_by('created').select_related()
pages = [content.page for content in qs]

This works fine, but is there a more straightforward way to do this?

Thanks,
Brad

--
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 django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment