-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create m2m_queries_how_many_objects_have_no_connections.md
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
33 changes: 33 additions & 0 deletions
33
django/m2m_queries_how_many_objects_have_no_connections.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
# Finding out how many objects have N connections to the other model in a M2M relationship | ||
|
||
Assume we have a model `Item` with a ManyToMany field to `Category` through `ItemCategory`. | ||
|
||
```python | ||
class Category(models.Model): | ||
... | ||
|
||
class Item(models.Model): | ||
categories = models.ManyToManyField("Category", through="ItemCategory"...) | ||
|
||
class ItemCategory(models.Model): | ||
item = models.ForeignKey("Item"...) | ||
category = models.Category("Category"...) | ||
``` | ||
|
||
We want to know how many Items do not have any Categories. | ||
|
||
```python | ||
from django.db.models import Count | ||
from items.models import Item | ||
|
||
# Annotate each item with the count of related categories | ||
items_with_category_count = Item.objects.annotate(categories_count=Count('categories')) | ||
|
||
# Filter items that have zero categories | ||
items_with_zero_categories = items_with_category_count.filter(categories_count=0) | ||
|
||
# Get the count of items with zero categories | ||
count_of_items_with_zero_categories = items_with_zero_categories.count() | ||
|
||
print(count_of_items_with_zero_categories) | ||
``` |