Reputation: 802
I am an android developer. I have an app which connects to MySql DB in server. Now i am planning to migrate them to Google app engine. But i am stuck with how to structure my entities.
There are tables 'users' and 'books'. Users can own multiple books and a book can be owned by multiple people. So there is a reference table called 'book-owners'. There is a column in this table called as the number of pages read. So each user to book relationship has a this special property 'no. of pages read'.
With MySql I could perform join queries to get all the info i want.Now with GAE we can not perform join queries. All I want is these,
When I query for user i need the following response:
{"user_id":"123","user_name":"John Doe","books":[{"book_id":"123456", "book_name":"Some book name","pages_read":126},{"book_id":"123457","book_name":"Some book name","pages_read":26},{"book_id":"123458","book_name":"Some book name","pages_read":274},{"book_id":"123459","book_name":"Some book name","pages_read":48}]}
So how to structure my entities. And how to query them back? Kindly give me some advice / pointers. Thanks already.
Upvotes: 0
Views: 65
Reputation: 16553
Here is one way:
class User(ndb.Model):
[any data here you want]
class Book(ndb.Model):
[any data here you want]
class OwnedBook(ndb.Model):
user = ndb.KeyProperty(User)
book = ndb.KeyProperty(Book)
pages_read = ndb.IntegerProperty()
To get books owned by a user with pages read, do this:
books_owned_by_user = OwnedBook.query(OwnedBook.user = user1)
After getting the OwnedBook
entities, you'll need to do further queries to get more information about the books.
for owned_book in OwnedBook.query(OwnedBook.user = user1):
book = owned_book.book.get()
You'll need to think about how to do this efficiently for your particular application.
To get the number of owners of a book, do this:
num_owners = OwnedBook.query(OwnedBook.book = book1).count()
Upvotes: 2