OJFord
OJFord

Reputation: 11130

Datastore query two entity kinds, on a common property?

Say I have two entity kinds:

class image(db.Model):
    url = db.LinkProperty()
    date= db.DateTimeProperty()

class video(db.Model):
    url = db.LinkProperty()
    date= db.DateTimeProperty()

Which each may have some other (unimportant here) properties.

What I want to do is somehow merge the queries:

i = image.gql('ORDER BY date LIMIT 10')
v = video.gql('ORDER BY date LIMIT 10')

Such that I am left with a single GqlQuery object that is the result as if image and video were the same kind.

Is it possible without doing something like:

merged = ([a for a in i] + [b for b in v]).sort(key=lambda x: x.date)[:10]

Being left with an actual GqlQuery object instead of a list of entities would be a plus, though I have everything I need from the latter.

Upvotes: 0

Views: 669

Answers (1)

Tim Hoffman
Tim Hoffman

Reputation: 12986

The only way with inheritance and different classes is to use a PolyModel then your class hierarchy would be

class Media(db.Model):
    url = db.LinkProperty()
    date= db.DateTimeProperty()

class Image(Media):
    pass

class Video(Media):
    pass 

Then in GQL and preferably Query objects

To get all media types

 query = Media.query().order(Media.date)

To just get Video

 query = Video.query().order(Video.date)

Or don't have different classes. Have a single Media class and a field that denotes a media type.

Docs for PolyModel can be found here - https://developers.google.com/appengine/docs/python/ndb/polymodelclass

Upvotes: 1

Related Questions