What is the alternative for back-reference property in NDB?

I read this question and a simple and clear answer, but it is not useful in my case, because the answer does not take into account the nested for . see code:

 class SuperCat(ndb.Model): class Category(ndb.Model): supercat = ndb.KeyProperty(kind=SuperCat) class SubCat(ndb.Model): category = ndb.KeyProperty(kind=Category) 

handler:

 Categories = ndb.gql("SELECT * FROM Category WHERE supercat = :1", supercat_key) self.generate('supercat.html', {'Categories': Categories}) 

in the template with the old db.Model and the back-reference property, it’s enough:

 {{ for Category in Categories }} {{ for SubCat in Category.subcat_set }} # this is the back-reference in action 

What is a simple alternative to serving such a data structure?

+6
source share
1 answer

Let's look at it systematically. Firstly, the db-> ndb translation guide tells us that a query returning SubCategory instances for a given instance of a category looks like this:

  subcats_query = SubCategory.query(SubCategory.category == cat.key) 

(Note that I use lowercase names for instances / entities and CapWords for classes / models. Thus, cat is a category entity.)

So, in Python, we will write your double loop as follows:

  for cat in categories: for subcat in SubCat.query(SubCat.category == cat.key): ...blah... 

To turn this into something easily accessible from the template, let's define a new method in the Category class:

  class Category(ndb.Model): supercat = ndb.KeyProperty(kind=SuperCat) def subcat_set(self): return SubCat.query(SubCat.category == self.key) 

Note that this is a method; in Python you should call it:

  for cat in categories: for subcat in cat.subcat_set(): ...blah... 

But in the template, you can (should) leave the call syntax () to get what you want:

  {{ for cat in categories }} {{ for subcat in cat.subcat_set }} ...blah... 

Give it a try!

+11
source

Source: https://habr.com/ru/post/918574/


All Articles