Order django request set by ManyToManyField = Value

If there are such models as:

class Tag(models.Model):
    name = models.CharField()

class Thing(models.Model):
    title = models.CharField()
    tags = models.ManyToManyField(Tag)

I can do a filter:

Thing.objects.filter(tags__name='foo')
Thing.objects.filter(tags__name__in=['foo', 'bar'])

But is it possible to order a request for the value of tags?

Thing.objects.order_by(tags__name='foo')
Thing.objects.order_by(tags__name__in=['foo','bar'])

What I would expect (or seemingly) in this example would be ALL THING, but ordered where they have the tag / tags that I know. I do not want to filter them out, but I bring them to the top.

I understand that this is possible using the FIELD operator, but it seems that I can only make it work with the columns in this model table, for example. title, but not on related tables.

Thank!

EDIT: After making the decision below, I realized the error / limitation.

Thing , (- , SQL), Thing , . True False , .

.distinct() , 2 Thing (.. tagged = True tagged = False).

, SQL, MAX() CASE(), GROUP BY Thing, , Thing, - match, tagged True ( False ).

, , - .values ​​() :

Thing.objects.values('pk').annotate(tagged=Max(Case(...)))

pk , Thing. , , , :

from django.db.models import Case, When, Max, BooleanField

tags = ['music'] # for example

queryset = Thing.objects.all().annotate(tagged=Max(Case(
    When(tags__name__in=tags, then=True),
    default=False,
    output_field=BooleanField()
)))
queryset.query.group_by = ['pk']
queryset.order_by('-tagged')

, , /. / ?

: (

+4
1

conditional , , ,

from django.db.models import Case, When, IntegerField

Thing.objects.annotate(tag_is_known=Case(
    When(tags__name__in=['foo', 'bar'], then=1),
    default=0,
    output_field=IntegerField()
))

, tag_is_known order_by():

Thing.objects.annotate(tag_is_known=...).order_by('tag_is_known')

Thing.objects.annotate(tag_is_known=Case(
    When(tags__name__in=['foo', 'bar'], then=True),
    default=False,
    output_field=BooleanField()
))
+4

All Articles