Reputation: 427
I have two models/tables A
and Property
. A
has a many to many relationship to Property
. A has one field SomeName
and Property
also has one field Value
.
Through my app, I receive a list of Values
. Now, I want to retrieve the A
rows who has at least one Value
from the sent list but I also want to sort those rows according to the number of Properties
present in the list.
For example, M, N and O are three objects of model A. M has the properties P1, P2, P3, N has the properties P2, P3, P4 and O has the properties P3. I receive a list of values P2, P4. Now, the resultant queryset I want is <QuerySet [<A: N>, <A: M>]>
if SomeName
is the string representation of model A.
Django code is preferred but SQL will also suffice.
Upvotes: 0
Views: 85
Reputation: 20359
Feels like you need. Assuming A
is the model and Values
is the field in Properties
.Also M2MField
is the Many2Many
field from A
to Property
.
A.objects.filter(M2MField__Values__in=[list that you have]).annotate(c=Count('M2MField')).order_by('c') #-c for descending order.
Upvotes: 2