2

This is my models.py

class Categories(db.Model):
__tablename__ ='categories'
parent = db.Column(db.String, nullable = False)
child = db.Column(db.String)
pid = db.Column(db.Integer, primary_key = True)

def __repr__(self):
    return f"Categories('{self.parent}', '{self.child}', '{self.pid}')"

def __init__(self, parent, child, id):
    self.parent = parent
    self.child = child
    self.id = id

This is my forms.py

existSelectParentField = QuerySelectField('Select Existing Categories',query_factory=parentcat_query, get_label= 'parent', description='Choose parent category')

This is my query factory

def parentcat_query():
parentcat = session.query(db.func.count(Categories.child), 
Categories.parent).group_by(Categories.parent).all()
return parentcat

But I get this error, sqlalchemy.orm.exc.UnmappedInstanceError: Class 'sqlalchemy.util._collections.result' is not mapped

What I'd like to do is display distinct values from my Categories.parent

I understand that I must return a table with a query factory and not just a column but in this case I am returning a table with two columns.

Is the error due to the fact that this 'new table' has not been mapped in my models.py?

Any suggestions on a workaround?

Krishan V
  • 83
  • 1
  • 6
  • It is not possible to select on specifics from your model in a QuerySelectfield, only additional filtering is possible (filter or filter_by). Have a look at this https://stackoverflow.com/questions/53885973/remove-duplicates-from-queryselectfield on how I solved it. Basically I created a custom QuerySelectField with specific code to remove duplicates. – gittert Jan 07 '19 at 15:48

1 Answers1

0

For those curious my work around was

distinctParent = db.session.query(db.func.count(Categories.child), Categories.parent).group_by(Categories.parent).order_by(Categories.parent).all()
existSelectParentField = SelectField('Select Existing Categories', validators=[Optional()], choices=list(distinctParent))

I essentially grouped by parent categories with the count function as the aggregate function. Not the best work around since in my dropdown menu, the ID of the selection would be the count.

Krishan V
  • 83
  • 1
  • 6