0

So I basically have a Django form to change ownership of an item, but users are showing up in a non-alphabetical and as of yet uncontrollable order.

class myModel(models.Model):
    owner = models.ForeignKey(User, null=True, blank=True)

Since I am using a built in model I can't for the life of me figure out how to get "owner" field to sort by the username when calling the form below.

class OwnerChange(ModelForm):
    required_css_class = 'required'
    class Meta:
        model = myModel
        fields = ['owner']
Joseph Dattilo
  • 835
  • 7
  • 9

1 Answers1

0

In your model form can easily override the queryset.

class OwnerChange(forms.ModelForm):
    required_css_class = 'required'

    ## Update the queryset to order by username 
    owner = forms.ModelChoiceField(queryset=User.objects.order_by('username'))

    class Meta:
        model = Cluster
        fields = ['owner']

Don't forget to update your import to

from django import forms

Another option you can use to not update all forms. However, the above example is useful if you don't want to sort all instances in the model in all queryset by username

class myModel(models.Model):
    owner = models.ForeignKey(User, null=True, blank=True)

    class Meta:
        ordering = ['owner__username']
Othman
  • 2,942
  • 3
  • 22
  • 31
  • Thank you so much! I would like to mention that the second option does not work. That would sort results of type myModel, not the results in the actual queryset for the foreign key. At least from what I tried. – Joseph Dattilo Aug 27 '15 at 00:17