views:

112

answers:

3

I have two models in the same application. The application is called "News", and it has two classes in its model called "Article" and "Category".

class Category(models.Model):
    name = models.CharField(_("Name"), max_length=100)
    slug = models.SlugField(_("Slug"), max_length=100, unique=True)

class Article(models.Model):
    category = models.ForeignKey(Category, verbose_name=_("Category"))
    archived = models.BooleanField(_("Archive this?"), default=False)

I want to create a query that shows me all of the articles which are archived but grouped by category.

How would I accomplish this efficiently?

+2  A: 
Article.objects.filter(archived=True).order_by('category')

i am editing this to get more info to try and help out.

given:

  • cat1
    • art1
    • art2-archived
    • art3
  • cat2
    • art4
    • art5
    • art6-archived
  • cat3
    • art7-archived
    • art8-archived
    • art9

what would you want your queryset to contain?

Brandon H
actually Category.objects.filter(article__archived=True) works.
@blackrobot: but you said you wanted `Articles`. Your query (assuming it works, I haven't tested it) will return `Categorys` that contain archived `Articles`. Brandon H's query will return a list of `Articles` ordered by `Category`.
Peter Rowell
Yeah, i wanted "grouped by category".
A: 

Isn't this what you want?

class Article(models.Model):
    category = models.ForeignKey(Category, related_name='articles')
    archived = models.BooleanField(default=False)

categories = Category.objects.select_related("articles").filter(articles__archived=True)
kibitzer
A: 

c = Category.objects.filter(article__archived=True)