Remove duplicates from QuerySelectField

£可爱£侵袭症+ 提交于 2020-01-06 07:53:34

问题


i'm running into issues with the following, and I'm wondering if it is even possible.

I have a flask-admin adminview setup, with an extra form field which shows a dropdown based on a specific column (category) in the sql model. See code for clarification:

model:

class Item(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(128), index = True)
    category = db.Column(db.String(16))

I have the extra form field in Flask-Admin as follows:

    form_extra_fields = {
    'category': QuerySelectField(
        label='Categories',
        query_factory = lambda: db.session.query(Item),
        get_label = 'category',
        )
    }

This all works fine except if there are duplicates in the category column, then the dropdown is populated with these duplicate values. Is it possible to remove those duplicates from dropdown, or at least only show the unique values?


回答1:


Basically I solved this by overriding a class method in QuerySelectField class as follows, by appending unique labels to a list and check if every next label is in that list. I'm still thinking there should be a better way though...

def iter_choices(self):
    labels = []     
    if self.allow_blank:           
        yield ('__None', self.blank_text, self.data is None)        

    for pk, obj in self._get_object_list():      

    if self.get_label(obj) not in labels:                        

        labels.append(self.get_label(obj))                
        yield (pk, self.get_label(obj), obj == self.data) 


来源:https://stackoverflow.com/questions/53885973/remove-duplicates-from-queryselectfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!