1

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)
1
  • That's a good solution, too. If you want to provide an even easier way to query by a particular field, you could just have a find_by_id or whatever. Commented Sep 8, 2013 at 14:40

1 Answer 1

5

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.