AppEngine Datastore get entities that have ALL items in list property

1k Views Asked by At

I want to implement some kind of tagging functionality to my app. I want to do something like...

class Item(db.Model):
  name = db.StringProperty()
  tags = db.ListProperty(str)

Suppose I get a search that have 2 or more tags. Eg. "restaurant" and "mexican".

Now, I want to get Items that have ALL, in this case 2, given tags.

How do I do that? Or is there a better way to implement what I want?

2

There are 2 best solutions below

9
On BEST ANSWER

I believe you want tags to be stored as 'db.ListProperty(db.Category)' and then query them with something like:

   return db.Query(Item)\
             .filter('tags = ', expected_tag1)\
             .filter('tags = ', expected_tag2)\
             .order('name')\
             .fetch(256)

(Unfortunately I can't find any good documentation for the db.Category type. So I cannot definitively say this is the right way to go.) Also note, that in order to create a db.Category you need to use:

new_item.tags.append(db.Category(unicode(new_tag_text)))
1
On

use db.ListProperty(db.Key) instead,which stores a list of entity's keys.

models:

 class Profile(db.Model):
 data_list=db.ListProperty(db.Key)

 class Data(db.Model):
 name=db.StringProperty()

views:

   prof=Profile()
   data=Data.gql("")#The Data entities you want to fetch

   for data in data:
       prof.data_list.append(data)

/// Here data_list stores the keys of Data entity

Data.get(prof.data_list) will get all the Data entities whose key are in the data_list attribute