从QuerySelectField删除重复项 [英] Remove duplicates from QuerySelectField

查看:218
本文介绍了从QuerySelectField删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下问题,我想知道是否有可能.

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

我有一个flask-admin adminview设置,带有一个额外的表单字段,该字段根据sql模型中的特定列(类别)显示一个下拉列表.参见代码以进行澄清:

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:

型号:

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))

我在Flask-Admin中有一个额外的表单字段,如下所示:

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?

推荐答案

基本上,我通过如下方法重写QuerySelectField类中的类方法,将唯一标签附加到列表中,并检查每个下一个标签是否在该列表中,从而解决了此问题.我仍然认为应该有更好的方法...

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) 

这篇关于从QuerySelectField删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆