Flask-SQLAlchemy.like () method raises NotImplementedError

I am unable to create a Flask-SQLAlchemy query with a method like()

that is supposed to build a query using an SQL statement LIKE

.

According to SQLAlchemy docs, the method LIKE

can be called on a column like this:

select([sometable]).where(sometable.c.column.like("%foobar%")) 

      

I have a ModelClass that subclasses the Flask-SQLAlchemy class db.Model

. Defined as follows:

class ModelClass(db.Model):
    # Some other columns ... 
    field1 = db.Column(db.Integer(), db.ForeignKey('my_other_class.id'))
    rel1 = db.relationship("MyOtherClass", foreign_keys=[field1])

      

Then I have a loop in which I create filters dynamically. Outside of the loop, I use these filters to filter the request. The inside of my loop, slightly modified, looks like this:

search_term = '%{}%'.format(search_string)
my_filter = getattr(ModelClass, field_string).like(search_term)

      

This throws an error in line with the method LIKE

:

NotImplementedError: <function like_op at 0x101c06668>

      

It throws this error for any text string. Python docs for NotImplementedError

says:

This exception is derived from RuntimeError. In userbase classes, abstract methods should throw this exception when they require derived classes to override the method.

It is not AttributeError

, so I think the method LIKE

exists, but something else is wrong and I'm not sure what.

Update

Now that I look in more detail at the model definition, I think the problem might be that I am doing this on a relation, not a type Column

.

I saw what type(getattr(ModelClass, field_string))

gives:

<sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x102018090>

      

Since it is not a type Column

, I looked at the values ​​for field_string

and saw that one of the passed values ​​actually was rel1

.

So, I think that the "answer", but I'm still confused why the call .like()

to rel1

not call AttributeError

.

+3


source to share


1 answer


So, I confirmed that the problem is that I am trying to apply a method .like()

to a relation attribute instead of a column.

I modified my code to call the child model class directly, rather than trying to navigate the relationship from the parent to access the columns of the child class. Something like that:



search_term = '%{}%'.format(search_string)
my_filter = getattr(ChildModelClass, field_string).like(search_term)

      

+2


source







All Articles