Question

I am trying to create a get method that passes key/value arguments to fetch objects.

def find_by_one(self, val, key='id'):
    obj = self.__model__.objects(key=val).first()
    return obj if obj else None

Error I get

InvalidQueryError: Cannot resolve field "key"

kindall answered my question. I ended up altering my method to pass **kwargs and passing this as my queryset

  def find_by_one(self, **kwargs):
    user = self.__model__.objects(**kwargs).first()
    return user if user else None

now I can just call my find_by_one

obj.find_by_one(id=obj_id)

instead of

obj.find_by_one(obj_id)
Was it helpful?

Solution

This means that your model does not have a field named key, which is what it's looking for because you are passing in key=val.

I'm assuming that you're looking for key to be replaced by the value of the key argument to the function. Keyword arguments do not work this way, so in this case you'll need to construct a dictionary and use unpacking:

obj = self.__model__.objects(**{key: val}).first()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top