Saturday 10 July 2021

Filter elements by optional lists of related elements

I have a feeling that I've made things more complex than they need to be - this can't possibly be such a rare case. It seems to me that it should be possible - or perhaps that I'm doing something fundamentally wrong.

The issue at hand is this: I've declared a database element, Element, which consists of about 10 many-to-many relations with other elements, one of which is Tag.

I want to enable the user of my application to filter Element by all of these relations, some of them or none of them. Say the user wants to see only Elements which are related to a certain Tag.

To make things even more difficult, the function that will carry out this objective is called from a graphql API, meaning it will recieve ID's instead of ORM objects.

I'm trying to build a resolver in my Python Flask project, using SQLAlchemy, which will provide an interface like so:

# graphql request
query getElements {
  getElements(tags:[2, 3] people:[8, 13]) {
    id
  }
}

# graphql response
{
  "data": {
    "getElements": [
      {
        "id": "2"
      },
      {
        "id": "3"
      },
      {
        "id": "8"
      }
    ]
  }
}

I imagine the resolver would look something like this simplified pseudo-code, but I can't for the life of me figure out how to pull it off:

def get_elements(tags=None, people=None):
  args = {'tags' : tags, 'people' : people}
  if any(args):
    data_elements = DataElement.query.filter_by(this in args) # this is the tricky bit - for each of DataElements related elements, I want to check if its ID is given in the corresponding argument
  else:
    data_elements = DataElement.query.all()
  
  return data_elements

Please, ORM wizards and python freaks, I call upon thee!



from Filter elements by optional lists of related elements

No comments:

Post a Comment