简体   繁体   中英

Django Count overlap of related objects and queryset/list

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?

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()
  )
))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM