calabash
calabash

Reputation: 453

How to remove duplicatates from wtforms QuerySelectField

In my Flask form I want to have a drop down list of unique items.Depending on what is selected will filter which items will appear in a second drop down (using javascript for this).

I have a database table something like this:

Category Sub-category Type
Application Can't log in Incident
Application Error Incident
Application Install Request
Application Remove Incident
Database Optimise Request
Database Corrupt Incident

and so on. So in the Category column there are multiple entries of the same name. Currently when I populate the QuerySelectField using this:

category = QuerySelectField(label='Category',
                               query_factory=lambda: Classification.query.filter_by(selectable=True),
                               allow_blank=True,
                               get_label='category', id='category', blank_text=u'Select a category...'
                                )

I get a list of everything in the Category column. But I only want to list one of each item. How can I do this?

I thought to use SelectField instead of QuerySelectField but could not figure out how to dynamically create the choices[].

Upvotes: 1

Views: 178

Answers (1)

calabash
calabash

Reputation: 453

I figured out how to do this if anyone else has this same use case.

I changed this:

category = QuerySelectField(label='Category',
                               query_factory=lambda: Classification.query.filter_by(selectable=True),
                               allow_blank=True,
                               get_label='category', id='category', blank_text=u'Select a category...'
                                )

to this:

category = QuerySelectField(label='Category',
                            query_factory=lambda: Classification.query.filter_by(selectable=True).distinct(Classification.category),
                            allow_blank=True,
                            get_label='category',
                            id = 'category',
                            blank_text = u'Select a category...'
                            )

The trick was adding the distinct(column you need to be distinct) part. In my case distinct(Classification.category)

Upvotes: 1

Related Questions