[FIXED] How Can I Sort These Many To Many Values Without a Through Table?

Issue

I am trying to compare the values ​​of two manytomany fields…this mostly works…

author_confirm = Author.objects.filter(id=self.object.update_reader_id).values_list('author_confirm').order_by('pk')
author = Author.objects.filter(id=self.object.update_reader_id).values_list('author').order_by('pk')
author_are_equal = list(author) == list(author_confirm)
author_are_not_equal = list(author) != list(author_confirm)
 

This works in terms of retrieving the value…but it doesn’t seem to work with order_by…currently both fields have the same value…but , will tell you these fields are not identical because their PKs are transposed…which is technically correct…but the problem is that the PKs are not listed in order I think…is there a way to do this without using a thru table?

I’m using a UUID as the primary key….I’m not sure if this is related…but despite that I can’t seem to get the values ​​in an ordered way.

Solution

You should order by the author__pk and author_confirmed__pk, otherwise you are only ordering by the author object itself, which we lready know: that is the self.object.update_reader_id, hence the problem:

author_confirm = (
    Author.objects.filter(id=self.object.update_reader_id)
    .values_list('author_confirm')
    .order_by('author_confirm__pk')
)
author = (
    Author.objects.filter(id=self.object.update_reader_id)
    .values_list('author')
    .order_by('author__pk')
)

Answered By – Willem Van Onsem

Answer Checked By – David Marino (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published