1 | initial version |
You can apply the order_by and distinct methods in Django's ModelChoiceField for forms by using the queryset parameter.
Here is an example:
# models.py
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
# forms.py
class BookForm(forms.Form):
author = forms.ModelChoiceField(
queryset=Author.objects.all().distinct().order_by('name')
)
# views.py
def my_view(request):
form = BookForm()
return render(request, 'my_template.html', {'form': form})
In the above example, we are applying the order_by method on the name field of the Author model and the distinct method on the queryset to remove any duplicate author names.