Mongoengine: How to determine an empty list in MongoEngine?

Created on 20 Sep 2018  路  5Comments  路  Source: MongoEngine/mongoengine

I have a field like this in a MongoDB table: "answers":[]

How can I do conditional branch if I want to know it is an empty list?

I'm using Python 2.7 and MongoEngine 0.15.0.

This is what I am trying to do: if object_name.answer is None:

Is that correct? Please point out if I am on the right track.

Most helpful comment

Not to nitpick, but for future readers, I suspect you meant to quote:

if not object_name.answer:
    ...

I suspect most folks would have figured that out, but just in case...

All 5 comments

Unless I'm misunderstanding the question, this is a general python question (unless you are asking for how to query through mongoengine).

It all depends:

  • If you don't mind whether it is None or [] (or anything else that evaluates to False) you can simply:
if object_name.answer:
    ...
  • If you need to separate the None from the empty list:
if object_name.answer == []:
   ...
elif object_name.answer is None:
    ...

@candycrusher does that answer your question? If yes, then let's close this :)

Not to nitpick, but for future readers, I suspect you meant to quote:

if not object_name.answer:
    ...

I suspect most folks would have figured that out, but just in case...

@candycrusher does that answer your question? If yes, then let's close this :)

Yes, absolutely did. I appreciate your help. Also, I would like to keep my pace to contribute to open source someday. The web greatwall in China makes me very hard to climb finally to here.

Not to nitpick, but for future readers, I suspect you meant to quote:

if not object_name.answer:
    ...

I suspect most folks would have figured that out, but just in case...

Exactly, that's what I need to note and keep this good habit.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ZEROF picture ZEROF  路  4Comments

BenCoDev picture BenCoDev  路  5Comments

adamlwgriffiths picture adamlwgriffiths  路  4Comments

kushalmitruka picture kushalmitruka  路  5Comments

lamiskin picture lamiskin  路  4Comments