Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-to-Many relationship in ndb

I am reading up on Google app engine and preparing a sample to understand it better.

In a nutshell the user can record an entry for every day in the month, like a calendar. And the user can view the entries on monthly basis. So no more than 30 ish at a time.

Initially I had used db and the one-to-many relationship was straight forward.

But once I came across the ndb, I realized there are two ways of modelling a one-to-many relationship.

1) The structured property seems to act like a repeated property on the User model. Does it mean if I retrieve one user, I would automatically retrieve all the records she has entered? (e.g. the entire year) This isn't very efficient though, is it? I guess the the advantage is that you get all related data in one read operation.

    from google.appengine.ext import ndb

    class User(UserMixin, ndb.Model):
        email = ndb.StringProperty(required = True)
        password_hash = ndb.TextProperty(required = True)
        record = ndb.StructuredProperty(Record, repeated=True)

    class Record(ndb.Model):            
        notes = ndb.TextProperty()

2) Alternatively I could use perhaps the more classic way:

    class User(UserMixin, ndb.Model):
        email = ndb.StringProperty(required = True)
        password_hash = ndb.TextProperty(required = True)

    class Record(ndb.Model):
        user = ndb.KeyProperty(kind=User)
        notes = ndb.TextProperty()

Which way is the better way in my use case?

like image 774
Houman Avatar asked Feb 17 '23 04:02

Houman


1 Answers

The downside of using StructuredProperty instead of KeyProperty is that with StructuredProperty the limit on total entity size (1MB) applies to the sum of the User and all Records it contains (because the structured properties are serialized as part of the User entity). With KeyProperty, each Record has a 1MB limit by itself.

like image 156
Guido van Rossum Avatar answered May 16 '23 08:05

Guido van Rossum