Order_by ManyToMany relation?

7 views
Skip to first unread message

Mei B

unread,
Jun 5, 2019, 5:13:07 PM6/5/19
to Django users
I have a form for a model that contains a ManyToMany relationship to model B.
By default, manytomany relationship on forms are SelectMuliple and orders them by alphabetical.
How can I order by if they already have a relation?

In my forms.py

class FormA(forms.ModelForm):
    class Meta:
        model = models.A

    def __init___(self, *args, **kwargs):
          super(FormA, self).__init__(*args, **kwargs)
          self.fields["b"].queryset = models.B.objects.order_by(???)

If model B has objects: "a, a1, a2, b, b2"
And model A has a many to many relationship with B's "a, a2, b2"
How can I order the objects so it'll show "a, a2, b2, a1, b" on the form?
Reply all
Reply to author
Forward
0 new messages