Dmitriy Kisil
Dmitriy Kisil

Reputation: 2998

Wrong alphabetical ordering by manytomany field in django

I am Django beginner and trying to figure it out why got wrong alphabetical ordering by m2m field when I have more than 2 records. Below provide dummy information for your better understanding.

Created from scratch models.py:

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=50)

class Publisher(models.Model):
    name = models.CharField(max_length=50)
    pub_authors = models.ManyToManyField(Author, blank=True)

After filling db with some data, tried simple query in python console for give all the publishers which are ordered by authors they have:

from app.models import Publisher
[print(i.pub_authors.all()) for i Publisher.all().order_by('pub_authors__name')]

Example of output when have only 1 author to each publisher(correct ordering):

<QuerySet [<Author: A>]>
<QuerySet [<Author: A>]>
<QuerySet [<Author: A>]>
<QuerySet [<Author: B>]>
<QuerySet [<Author: C>]>

Example of output when have more than 1 author to each publisher(wrong ordering):

<QuerySet [<Author: A>]>
<QuerySet [<Author: A>]>
<QuerySet [<Author: A>, <Author: B>]>
<QuerySet [<Author: A>]>
<QuerySet [<Author: B>]>
<QuerySet [<Author: B>, <Author: A>]>
<QuerySet [<Author: B>, <Author: C>]>
<QuerySet [<Author: B>]>
<QuerySet [<Author: A>, <Author: C>]>
<QuerySet [<Author: C>]>

Expected results:

<QuerySet [<Author: A>]>
<QuerySet [<Author: A>]>
<QuerySet [<Author: A>]>
<QuerySet [<Author: A>, <Author: B>]>
<QuerySet [<Author: A>, <Author: C>]>
<QuerySet [<Author: B>]>
<QuerySet [<Author: B>]>
<QuerySet [<Author: B>]>
<QuerySet [<Author: B>, <Author: C>]>
<QuerySet [<Author: C>]>

Hope you can pointed me at right direction, why this could happen at least(can't solve it for a week, very struggling on it)

Updated: I provided wrong expected results(sorry), update it. I see that I need to clarify a little: I am got incorrect order between Publisher querysets, not inside each Publisher. So I'm worried when Publisher queryset with [A,B] authors placed before Publisher with [A] authors. Or Publisher with [A,C] placed between [B] and [C]

Upvotes: 2

Views: 124

Answers (1)

Dmitriy Kisil
Dmitriy Kisil

Reputation: 2998

Using from django.contrib.postgres.aggregates import StringAgg helps here

Upvotes: 0

Related Questions