title: Flask SQLAlchemy: How to find the primary key value before adding a new object to the session?
body: <p>I'm using <code>b64encode</code> to create a unique reference string from the primary key in each row in the table. This is my model in Flask SQLAlchemy:</p>
  <pre><code>class Groups(db.Model):
      id = db.Column(db.Integer, primary_key = True)
      ref_id = db.Column(db.String(20), index = True)
  
      def __init__(self):
          self.ref_id = id_encode(self.id)
  </code></pre>
  <p>However, the <code>self.id</code> passed into the <code>id_encode()</code> function has a &quot;None&quot; value instead of the primary key's value. From what I can see, it's only possible to get the new primary key value after committing the session, or by <a href="https://stackoverflow.com/questions/41750755/get-primary-key-from-sqlalchemy-before-commit-the-object">using the flush() method</a>.</p>
  <p>Here's the definition for <code>id_encode()</code>:</p>
  <pre><code>def id_encode(num):
          bts = base64.b64encode(bytes(str(num), 'utf-8'))
          print(num)
          return bts.decode()
  </code></pre>
  <p>If there any way to get this to work, or what's a better (but simple) way to do unique reference ID generation? I just don't want the average user to be able to navigate to other groups by entering a numeric ID.</p>