0

I'd like to mark some columns in my entities as Searchable -- ideally in a clean way, on a per-column basis. Is it possible to "tag", or add a property to the column definition in the class? Elsewhere in the code, I'd like to be able to pick up the columns that are searchable on any entity, without knowing what class it is specifically.

eg:

class Foo(Entity):
  bar = Field(Integer, default = -1, searchable = True)

..

if foo.bar.searchable:
  # do something

Obviously the above example doesn't work -- but is there a way to do this? I'm not an expert in this, and a couple of days of search / doc trawling revealed nothing helpful.

Ben
  • 51,770
  • 36
  • 127
  • 149
btk
  • 3,158
  • 2
  • 29
  • 30

1 Answers1

0

Monkeypatching works (at least in sqlalchemy declarative models, I haven't tried it with Elixir), though it exposes you to all of the standard problems with monkeypatching (the main one being that there's no guarantee that your modification to bar will remain unaltered). But it basically works, and could be a viable solution if your application is very simple.

class Foo(Entity):
    bar = Field(Integer, default=-1)
    bar.searchable = True

If your application is more complex, and/or it needs to be robust/reliable/maintainable-by-many over a long time, the above technique is not the way to go. Ideally you want to introduce some other object to store this additional info, an object that is completely within your control, and not at the mercy of all the behind-the-scenes stuff that sqlalchemy does with your data model classes.

For that purpose there are many ways to go. One easy choice is just to create a simple structure which will hold the additional information (boolean 'searchable' property and anything else you might want to add) in such a way that you can look it up easily when needed. For example, define a very simple class which uses nested dict()s to store any number of additional properties indexed by model class, Field name, and property name. Then create a single instance of this class, and share it throughout your app.

Having set up such a structure, you could then make use of it like so:

if extra_props[foo]['bar']['searchable']:
    # do something
cdaddr
  • 1,330
  • 10
  • 9