Reputation: 860
Say I have a model:
class Car(models.Model):
name = models.CharField()
parts = models.ManyToManyField(Part)
Now in my queryset of Car objects (Car.objects.all()) I want to annotate the count of overlap of parts in my list of ids or my queryset of Parts.
So let's say I have two Car objects:
{
name: 'car1',
parts: [1,2,3,4]
}
{
name: 'car2',
parts: [1,5,6,7]
}
Then I want the following output from my query with list [1,2,3]
{
name: 'car1',
parts: [1,2,3,4],
parts_overlap: 3
}
{
name: 'car2',
parts: [1,5,6,7],
parts_overlap: 1
}
I need ti like this because I want to order_by it.
Is this possible?
Upvotes: 0
Views: 738
Reputation: 860
I found it out.
from django.db.models import Count, Case, When, IntegerField
queryset.annotate(parts_overlap=Count(
Case(
When(parts__in=list, then=1),
output_field=IntegerField()
)
))
Upvotes: 1