1

My query looks like:

employee = Partner_employees.objects()\
            .filter(id=user_id) \
            .filter(earnings__gte=preconditions.earnings.gte) \
            .filter(earnings__lte=preconditions.earnings.lte) \
            .filter(work_rating__gte=preconditions.credit_score) \
            .filter(employment_status=preconditions.employment_status) 

now there are plans which have employment_status in preconditions and some don't.

Example :

employment_status in preconditions

plan B : val(preconditions.employment_status ) = True

employment_status not in preconditions

plan A : val(preconditions.employment_status ) = None

user info:

userA : val(employment_status)= True

userB: val(employment_status)= False

so I want userA and userB in query result for PlanA (this fails)

userA in query result for planB(this works)

Community
  • 1
  • 1

1 Answers1

1

This is an unfortunate aspect of MongoEngine. Often default values don't get explicitly written to the DB (or if you added the default after some records are there). I see a few options:

  1. Explicitly set the false records to False and save them. Then the query should work. This would need to be done on records already in the DB.

  2. Query for False or None. You can use the or feature like this. This answer covers it I think: MongoDB using an OR clause in mongoengine

For you example, I would think it goes like:

employee = Partner_employees.objects()\
            .filter(id=user_id) \
            .filter(earnings__gte=preconditions.earnings.gte) \
            .filter(earnings__lte=preconditions.earnings.lte) \
            .filter(work_rating__gte=preconditions.credit_score) \
            .filter(Q(employment_status=False or Q(employment_status=None)) 

I'm not sure which way the default value went, but you can always do this. I'm assuming the default value is False:

query = ... # same as above but not test for employment_status
if preconditions.employment_stats:
   query = query.filter(employment_status=True)
else:
   query = query.filter(Q(employment_status=False or Q(employment_status=None))

return query.first()
Michael Kennedy
  • 3,202
  • 2
  • 25
  • 34
  • 1
    I think I was a little unclear in the question, function definition looks like: '''def find_credit_dcsn(user_id:str,preconditions:Preconditions) -> Partner_employees''' the issue is I want to handle the case when preconditions.employment_status = None while querying for Partner_employees.objects() – Sachin Tripathi May 08 '20 at 16:32