Determine if an entity is created 'today'
<p>I am creating an app which, on any given day, only one entity can be created per day. Here is the model:</p>

<pre><code>class MyModel(ndb.Model):
    created = ndb.DateTimeProperty(auto_now_add=True)
</code></pre>

<p>Since only one entity is allowed to be created per day, we will need to compare the MyModel.created property to today's date:</p>

<pre><code>import datetime

class CreateEntity(webapp2.RequestHandler):
    def get(self):
        today = datetime.datetime.today()
        my_model = MyModel.query(MyModel.created == today).get()

        if my_model:
          # print("Today's entity already exists")
        else:
          # create today's new entity
</code></pre>

<p>The problem is that I cannot compare the two dates like this. How can I check if an entity was already created 'today'?</p>

<p>Using a range query for a single specific known value you want to lookup is overkill and expensive, I would use one of these 2 solutions:</p>

<p><strong>1 - Extra Property</strong></p>

<p>Sacrifice a little space with an extra property, though since it's one per day, it shouldn't be a big deal.</p>

<pre class="lang-python prettyprint-override"><code>from datetime import datetime


class MyModel(ndb.Model):

    def _pre_put_hook(self):
        self.date = datetime.today().strftime("%Y%m%d")

    created = ndb.DateTimeProperty(auto_now_add=True)
    date = ndb.StringProperty()


class CreateEntity(webapp2.RequestHandler):

    def get(self):
        today = datetime.today().strftime("%Y%m%d")

        my_model = MyModel.query(MyModel.date == today).get()

        if my_model:
            logging.info("Today's entity already exists")
        else:
            # MyModel.date gets set automaticaly by _pre_put_hook
            my_model = MyModel()
            my_model.put()
            logging.info("create today's new entity")
</code></pre>

<p><strong>2 - Use [today] as Entity ID (preferred)</strong></p>

<p>I would rather use <code>today</code> as the <strong>ID</strong> for my Entity, that's the fastest/cheaper/optimal way to retrieve your entity later. It could also be a combination with something else, i.e. <code>ID=&lt;userid+today&gt;</code>, in case that entity is per user, or maybe just add userid as a parent (ancestor). So it would be something like this:</p>

<pre class="lang-python prettyprint-override"><code>from datetime import datetime


class MyModel(ndb.Model):
    created = ndb.DateTimeProperty(auto_now_add=True)


class CreateEntity(webapp2.RequestHandler):

    def get(self):
        today = datetime.today().strftime("%Y%m%d")

        my_model = MyModel.get_by_id(today)

        if my_model:
            logging.info("Today's entity already exists")
        else:
            my_model = MyModel(id=today)
            my_model.put()
            logging.info("create today's new entity")
</code></pre>

python google-app-engine datetime google-cloud-datastore app-engine-ndb