logo
down
shadow

SQLAlchemy Determine If Unique Constraint Exists


SQLAlchemy Determine If Unique Constraint Exists

Content Index :

SQLAlchemy Determine If Unique Constraint Exists
Tag : python , By : kema
Date : November 23 2020, 09:01 AM

Any of those help You could use SQLalchemy reflection API.
In order to get the unique constraints, issue a get_unique_constraints.
CREATE TABLE user (
    id INTEGER NOT NULL, 
    name VARCHAR(255), 
    email VARCHAR(255), 
    login VARCHAR(255), 
    PRIMARY KEY (id), 
    UNIQUE (email), 
    UNIQUE (login)
)
from sqlalchemy import create_engine
from sqlalchemy.engine.reflection import Inspector

# engine = create_engine(...)

insp = Inspector.from_engine(engine)

print "PK: %r" % insp.get_pk_constraint("user")
print "UNIQUE: %r" % insp.get_unique_constraints("user")
PK: {'name': None, 'constrained_columns': [u'login']}
UNIQUE: [{'column_names': [u'email'], 'name': None}, {'column_names': [u'login'], 'name': None}]
pk = insp.get_pk_constraint("user")['constrained_columns']
unique = map(lambda x: x['column_names'], insp.get_unique_constraints("user"))

for column in ['name', 'id', 'email', 'login']:
    print "Column %r has an unique constraint: %s" %(column, [column] in [pk]+unique)
Column 'name' has an unique constraint: False
Column 'id' has an unique constraint: True
Column 'email' has an unique constraint: True
Column 'login' has an unique constraint: True
from sqlalchemy import create_engine, Column, types
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session

Base = declarative_base()

class User(Base):
    __tablename__ = "user"
    id = Column(types.Integer, primary_key=True)
    name = Column(types.String(255))
    email = Column(types.String(255), unique=True)
    login = Column(types.String(255), unique=True)

# do not create any table
#engine = create_engine('sqlite:///:memory:', echo=True)
#session = scoped_session(sessionmaker(bind=engine))
#Base.metadata.create_all(engine)

# check if column is (any) a primary_key or has unique constraint
# Note1: You can use User.__table__.c too, it is a alias to columns
# Note2: If you don't want to use __table__, you could use the reflection API like:
#        >>> from sqlalchemy.inspection import inspect
#        >>> columns = inspect(User).columns
result = dict([(c.name, any([c.primary_key, c.unique])) for c in User.__table__.columns])

print(result)
{'email': True, 'login': True, 'id': True, 'name': False}
for column_name in ['name', 'id', 'email', 'login']:
    c = User.__table__.columns.get(column_name)
    print("Column %r has an unique constraint: %s" %(column_name, any([c.primary_key, c.unique])))
Column 'name' has an unique constraint: False
Column 'id' has an unique constraint: True
Column 'email' has an unique constraint: True
Column 'login' has an unique constraint: True

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to model a `UNIQUE` constraint in SQLAlchemy?


Tag : python , By : Marc
Date : March 29 2020, 07:55 AM
may help you . The first part of the question (about creating a unique constraint with multiple columns) is already answered by cleg.
However, the default many-to-many approach doesn't work if you want to have additionally columns in the mapping table. Instead, you should use the Association Object Pattern. Additionally, you can simplify the access between user and group with an association_proxy.

SQLAlchemy: UNIQUE constraint failed error, yet no unique constraints set


Tag : python , By : Bobblegate
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Drop your tables or delete your DB and initialize it again. Every time you make a schema change you must drop your tables and re-initialize, it doesn't just update.

flask sqlalchemy unique constraint not working


Tag : development , By : user92243
Date : March 29 2020, 07:55 AM
This might help you You have to add clause nullable=False to your username column declaration:
username = db.Column(db.String(64), unique=True, index=True, nullable=False)

python SQLAlchemy many to many unique constraint only working one way


Tag : python , By : Ed.
Date : March 29 2020, 07:55 AM
wish of those help I am using python 2.7 with sqlAlchemy over sqllite, in a flask app, and trying to map a relationship between two models, the models are Lad and Crew, a Lad can have many crews and vice verse, the only limitation is that the pair should be unique, e.g A lad can only be in a crew once and vice verse, I've built the models, and when trying to add a crew to the same lad twice, the primary key constraint is limiting me, but when trying to add the same lad to a crew twice, it let's me, which should also be forbidden. , The problem was solved by using
db_session.add(c)
db_session.add(l)
c.lads.append(lad)
c.lads.append(lad)
l.crews.append(c)
l.crews.append(c)
db_session.refresh(lad)
db_session.refresh(c) 

UNIQUE constraint failed in SQLAlchemy


Tag : python , By : Doug
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • How to create a pool of threads
  • Pandas giving IndexError on one dataframe but not on another similar dataframe
  • Django Rest Framework - Testing client.login doesn't login user, ret anonymous user
  • Running dag without dag file in airflow
  • Filling across a specified dimension of a numpy array
  • Python populating dataframe in pandas from text files
  • How to interpolate a single ("non-piecewise") cubic spline from a set of data points?
  • Divide 2 integers (leetcode 29) - recursion issue
  • Can someone explain why do I get this output in Python?
  • How do I scrape pdf and html from search results without obvious url
  • Is there a way to automatically make a "collage" of plots with matplotlib?
  • How to combine multiple rows in pandas with shared column values
  • How do I get LOAD_CLASSDEREF instruction after dis.dis?
  • Django - How to add items to Bootstrap dropdown?
  • Linear Regression - Does the below implementation of ridge regression finding coefficient term using gradient method is
  • How to drop all rows in pandas dataframe with negative values?
  • Most Efficient Way to Find Closest Date Between 2 Dataframes
  • Execution error when Passing arguments to a python script using os.system. The script takes sys.argv arguments
  • Looping through a function
  • Create a plot for each unique ID
  • a thread python with 'while' got another thread never start
  • Solution from SciPy solve_ivp contains oscillations for a system of first-order ODEs
  • trigger python events driven by selenium controlled browser
  • Passing line-edits to a contextmanager to set validators
  • Python: globals().items() iterations try to change a dict
  • Is it possible to specify starting values for each parameter (instead of bounds) for scipy's differential evolution?
  • why datetime.now() and constructed datetime using all fields(like year,month...) of now has big timedelta?
  • MySQL multiple table UPDATE query using sqlalchemy core?
  • find if a semantic version is superset of of another version python
  • Type checking against dynamically created objects
  • Struggling with simple reverse function
  • Is there a function for finding the midpoint of n points on sklearn.neighbors.NearestNeighbors?
  • How to set max number of tweets to fetch
  • PYTHON 3.7.4 NOT USING SQLITE 3.29.0
  • How to replace Nan value with zeros in a numpy array?
  • How to speed up calculating variance among sparse matrix
  • cupy code is not fast enough compared with numpy
  • How to count frequency of select values in Python pandas dataframe
  • Scrape Span Text from Google
  • Python watchdog, watch a directory and rename file on event.modification
  • Filtering rows in DataFrame with dependent conditions
  • How to check if a character is a not a part of number or URL in string?
  • Compare corresponding elements of a list
  • Python misinterprets 3 character string as UTF-8 continuation byte
  • Merge two columns in Pandas
  • Side Effect error in Python in an online compiler
  • How to convert a navigation list with depth levels to a parent-child flat list?
  • Retrieving values from a paired key dictionary in Python
  • How to test the current text of a Tkinter text box widget before inserting new text after user clicks on a button?
  • computing the Cumulative Sum, where Sum can be reset by a condition
  • Where do you specify your API key when making a request with the Google API python library?
  • Pandas DataFrame, computing the Time Difference between one row and other row which satisfies a condition
  • Discord.py bot not reading other bot's messages
  • How do I write a Django query that finds words in a Postgres column?
  • Download S3 File Using Boto3
  • Retrieve status of model training after closing notebook
  • If Current Date is in Column Then Show Row
  • How do I stay in a for loop's element until a condition is met?
  • QPainter point size is 1 pixel and can not be changed
  • How to download the excel file which has no link in Beautifulsoup?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com