I need help in using the class method example get_by_user My adaptation of the class method is next.
class Pages(ndb.Model):
user_id = ndb.StringProperty()
name = ndb.StringProperty()
@classmethod
def get_by_user(cls, user):
return cls.query().filter(cls.user_id == user.user_id()).get()
view.py code is next.
class MainPage(BaseHandler):
def get(self):
user = users.get_current_user()
logging.info("MainPageGet: %s " % user)
if user: #offer user options
isUser = True
user_ID = user
for p in Pages.query():
logging.info("MainPageGet p: %s " % p.user_id)
logging.info("MainPageGet user_ID: %s " % user_ID)
page = Pages.get_by_user( user_ID)
logging.info("MainPageGet page: %s " % page )
And my log results are the following.
<pre>
INFO 2018-02-10 04:28:21,509 views.py:192] MainPageGet: [email protected]
INFO 2018-02-10 04:28:21,518 views.py:198] MainPageGet p: [email protected]
INFO 2018-02-10 04:28:21,519 views.py:198] MainPageGet p: [email protected]
INFO 2018-02-10 04:28:21,519 views.py:200] MainPageGet user_ID: [email protected]
INFO 2018-02-10 04:28:21,524 views.py:204] MainPageGet page: None
INFO 2018-02-10 04:28:21,535 module.py:812] default: "GET / HTTP/1.1" 200 2284
</pre>
My sample ndb data is produced as follows.
page1 = Pages(id='BS',user_id='[email protected]',name='Brian')
page2 = Pages(id='JS',user_id='[email protected]',name='Joan')
page1.put()
page2.put()
So, my question is, what am I doing wrong that is producing the None result in the final logging result instead of locating the test.example.com result for the id='BS'?
The user.user_id() returns an ID, which at least on the development server is a numeric value, like this one: 185804764220139124118.
But when you created your Pages entities you set the values of their user_id property to a string containing an email address: user_id='[email protected]'.
Because of this the query inside get_by_user() won't return any entity, as none matches the filter.
You could modify get_by_user() to something like this (you may want to adjust the actual property name in this case, to avoid confusion):
@classmethod
def get_by_user(cls, user):
return cls.query().filter(cls.user_id == user.email()).get()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With