Reputation: 12181
I've created a simple DB using SQLAlchemy in python and there is a column for a unique user ID for each user entered. I want to have a running counter that supplies the next ID whenever a new User is added.
What would be the best way to implement this? A column with the value of the last id number, or would that be an entirely separate table (seems wasteful.) Is there a way for it to check the last User.id and add one? Here is the User base class:
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key = True)
email_address = Column(String, nullable = False)
username = Column(String, nullable = False)
password = Column(String, nullable = False)
first_name = Column(String)
full_name = Column(String)
join_date = Column(DateTime, default=func.now()) # enters the time upon initialization
def __init__(self, email_address, username, password):
self.email_address = email_address
self.username = username
self.password = password
def __repr__(self):
return "<User('%s', '%s', '%s', '%s')>" % (self.email_address, self.username, self.password, self.join_date)
Upvotes: 1
Views: 3330
Reputation: 7102
id will take unique value automatically after flushing newly created object to DB, so, as I know, you must run session.flush() if you need user id right now:
>>> user = User(email_address, username, password)
>>> print user.id
None
>>> session.add(user)
>>> session.flush()
>>> print user.id
100500
Also, please, don't use this terrible __init__
methods! You need a custom init only if you want to add a some custom logic or validation on it. But such simple cases as assigning keyword arguments as corresponding object attributes already provided by declarative_base
class (Base).
Upvotes: 0
Reputation: 107
What database are you using? If it's MySQL you might be done already. Try creating a User where User.id = None. It should take the next available id. If it is autoincrementing, after inserting the User the correct id will be placed in the User.id.
I normally create my schema outside of SQLAlchemy. What you want is for the id column to be the primary key, not null, and set to autoincrement. Then, if you don't assign an id it will take the next id automatically.
Upvotes: 0
Reputation: 391818
Read this: http://www.sqlalchemy.org/docs/core/schema.html#defining-sequences.
Key generation is a part of the database.
You simply want the database to assign unique keys.
Upvotes: 5