Complex Django query over foreign keys
-
19-09-2019 - |
Question
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?
Solution 2
c = Category.objects.filter(article__archived=True)
OTHER TIPS
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?
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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow