Search code examples
pythonpython-3.xnosqlgoogle-cloud-datastoregoogle-cloud-sdk

Unable to use query.Or() and other functions in google cloud datastore sdk


I was going thru the google cloud datastore docs. When I came across this code snippet

query_filter = query.Or(
    [
        query.PropertyFilter("starred", "=", True),
        query.And([query.PropertyFilter("done", "=", False),
                    query.PropertyFilter("priority", "=", 4,),
        ]
        )   
    ]
)

This would be incredibly useful in my current project. However when I tried using it I got the following error.

AttributeError: 'Query' object has no attribute 'Or'

At first, I assumed it was due to me having an outdated version, so I updated with pip. below is an excerpt from my requirements.txt

google-cloud-datastore>=2.15.1
google-cloud-storage>=2.8.0

No cigar, so I tried updating my sdk with gcloud components update

But it still doesn't let me use query.Or(). Nor does it let me use other features like IN in query.add_filter('id', 'IN', 'id_list')

I've tried, but I can't figure out what's wrong. All the other functions work as expected.

Here's the code where I get the error. Am I calling on the wrong object?

query = datastore_client.query()
query.Or()

Solution

  • From the documentation, your code should use datastore.query i.e.

    query_filter = datastore.query.Or(
        [
            datastore.query.PropertyFilter("starred", "=", True),
            datastore.query.And([datastore.query.PropertyFilter("done", "=", False),
                        datastore.query.PropertyFilter("priority", "=", 4,),
            ]
            )   
        ]
    )
    

    If you want to use the code as written in the documentation you referenced, then you have to first do

    from google.cloud.datastore import query