How to implement “autoincrement” on Google AppEngine

前端 未结 9 821
面向向阳花
面向向阳花 2020-11-27 16:23

I have to label something in a \"strong monotone increasing\" fashion. Be it Invoice Numbers, shipping label numbers or the like.

  1. A number MUST NOT BE used twi
9条回答
  •  感情败类
    2020-11-27 17:13

    I implemented something very simplistic for my blog, which increments an IntegerProperty, iden rather than the Key ID.

    I define max_iden() to find the maximum iden integer currently being used. This function scans through all existing blog posts.

    def max_iden():
        max_entity = Post.gql("order by iden desc").get()
        if max_entity:
            return max_entity.iden
        return 1000    # If this is the very first entry, start at number 1000
    

    Then, when creating a new blog post, I assign it an iden property of max_iden() + 1

    new_iden = max_iden() + 1
    p = Post(parent=blog_key(), header=header, body=body, iden=new_iden)
    p.put()
    

    I wonder if you might also want to add some sort of verification function after this, i.e. to ensure the max_iden() has now incremented, before moving onto the next invoice.

    Altogether: fragile, inefficient code.

提交回复
热议问题