Ask Your Question
2

How can I apply the order_by and distinct methods in Django's ModelChoiceField for forms?

asked 2023-06-19 14:22:44 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-19 14:50:01 +0000

qstack gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-19 14:22:44 +0000

Seen: 13 times

Last updated: Jun 19 '23