How do I order a model, based on multiple values of a ManyToManyField?

19 views
Skip to first unread message

Sem Verbraak

unread,
Jun 7, 2016, 5:57:37 AM6/7/16
to Django users

Basically, I need to order, based on multiple values from a ManyToManyField.


So what I want to achieve is having the objects with the most questioned values on top, continuing with objects that have less of the questioned values. Continuing with objects that don't have any of these values.


The models:



class Color(models.Model):
    name
= models.CharField(max_length=200)


class Item(models.Model):
    surface_color
= models.ManyToManyField(Color)


The instances created which are based on the models above:

  • Item 1) surface_color=[1, 2, 3]
  • Item 2) surface_color=[1, 2]
  • Item 3) surface_color=[2]
  • Item 4) surface_color=[1, 3]

Now I need to order based multiple colors:


Fake query: 

Item.objects.all().order_by(surface_color_id=[1, 3])

The query should have the following results:

  1. Item 4, since it has both 1 and 3 (2 matches)
  2. Item 1, since it has both 1 and 3 (2 matches)
  3. Item 2, since it has 1 (1 match)
  4. Item 3, since it has none (0 matches)

Is this possible with a single queryset? Or do I need to spam multiple queries for each combination?


The only things I found on the internet were about ordering multiple fields, this is about values.


Any help is appreciated.

Reply all
Reply to author
Forward
0 new messages