Rookie Rookie - 1 month ago 8
Python Question

Datastore Model for Complex access management with different sorting options

I have two datastore model, Group & Products. Products contains two category: Secure & Non Secure. And Each product belongs to a group.

We have 3 type of users: Admin, Normal Users and Group Members (A user can belongs to more than one group).

Admin users have access to all the groups. Normal users(Not belong to any group) have access to only Non Secure products.
Group Members have access to all the products of the groups which he belongs to and All non secure products of groups which he not belongs to.

And We need to query the list of products based on the datastore cursor to fetch 15 records at a time and results should be ordered by last_updated_date.

For Admin, Query:

PRODUCT.query().fetch_page(25, start_cursor=cursor).order(-PRODUCT.last_updated_date)


For Normal User, Query:
PRODUCT.query(PRODUCT.secure=False).fetch_page(25, start_cursor=cursor).order(-PRODUCT.last_updated_date)


I'm little confused about the query for Group members which basically have 'IN' operator, Non equality operator and sorting on last_updated_date. How to write a query to retrieve results for a user who belongs to Group: G1, G3, G5 ?

Probably the SQL query looks like this

Select * from Product where Group IN ( Select GroupID from User where email='a@a.com')

UNION

Select * from Product where Secure = No


Please help me write a NDB Datastore Query with sort by last_updated_date.

Answer

Try this:

group_ids_of_user = ['G1', 'G3', 'G5']
query = Product.query(ndb.OR(Product.secure == False,
                             ndb.AND(Product.secure == True, Product.group.IN(group_ids_of_user))))
Comments