I'm trying to create objects in Postgres db.
I'm using this approach https://websauna.org/docs/narrative/modelling/models.html#uuid-primary-keys
class Role(Base):
__tablename__ = 'role'
# Pass `binary=False` to fallback to CHAR instead of BINARY
id = sa.Column(UUIDType(binary=False), primary_key=True)
But when I create object
user_role = Role(name='User')
db.session.add(user_role)
db.session.commit()
I have the following error:
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) null value in column "id" violates not-null constraint
Looks like I didn't provide any ID. So, how I can make the database auto-generate it or generate on my own?
A UUID (universally unique identifier) is a 128-bit number that is generated with an algorithm that effectively guarantees uniqueness. There are several standardized algorithms for that. In PostgreSQL, there are a number of functions that generate UUID s: The uuid-ossp extension offers functions to generate UUID s.
As of Typeorm version 0.1.16, the decorator @PrimaryGeneratedColumn supports uuid for all databases. If your version of Postgres doesn't already include uuid-ossp (used to generate the UUID), you can install it using create extension "uuid-ossp";.
How to Generate a UUID in Python. The Python language has built-in support for generating Version 1, 3, 4 and 5 UUIDs. Here's an example of how you can create a Version 4 UUID in Python code. import uuid. myuuid = uuid.uuid4()
If your version of Postgres doesn't already include uuid-ossp (used to generate the UUID), you can install it using create extension "uuid-ossp";. Show activity on this post.
You appear to be using this code. It's missing a default for the column. You're emulating this SQL:
id UUID PRIMARY KEY DEFAULT uuid_generate_v4()
But you've already linked to the correct code.
id = Column(UUID(as_uuid=True),
primary_key=True,
server_default=sqlalchemy.text("uuid_generate_v4()"),)
Alternatively if you don't want to load a Postgres UUID extension, you can create the UUIDs in Python.
from uuid import uuid4
id = Column(UUID(as_uuid=True),
primary_key=True,
default=uuid4,)
You could use the uuid
module and just set a column default. For example:
from uuid import uuid4
from sqlalchemy import Column, String
class Role(Base):
__tablename__ = 'role'
id = Column(String, primary_key=True, default=uuid4)
What I actually came to is:
import uuid
class SomeClass(db.Model):
__tablename__ = 'someclass'
id = db.Column(UUID(as_uuid=True),
primary_key=True, default=lambda: uuid.uuid4().hex)
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