In the following code snippet, In the events table event_id is created first and then i need to insert multiple records into even_logins table based on the event_id.
class Events(db.Model):
__tablename__ = 'events'
event_name= db.column(db.String(100))
event_id = db.Column(db.String(10),primary_key=True)
scheduled_date = db.Column(db.DateTime, nullable = False)
event_logins_event_id = db.Column(db.String(10), db.ForeignKey('event_logins.event_id'))
event_registrations_event_id = db.Column(db.String(10), db.ForeignKey('event_registrations.event_id'))
class Event_logins(db.Model):
__tablename__ = 'event_logins'
event_id= db.column(db.String(10),db.ForeignKey('events.event_id'))
username = db.Column(db.String(20),primary_key=True)
password = db.Column(db.String(300))
class Event_registrations(db.Model):
__tablename__ = 'event_registrations'
event_id= db.column(db.String(10), db.ForeignKey('events.event_id'))
registration_id = db.Column(db.String(50),primary_key=True)
cust_name = db.Column(db.String(100))
cust_contactno = db.Column(db.String(50))
cust_email = db.Column(db.String(50))
cust_imageid = db.Column(db.String(200))
Finally with the below query am trying insert a record into event_logins table
event_logins = Event_logins(event_id='jk12',username='testuser', password='aaaa')
db.session.add(event_logins)
db.session.commit()
In the table it is stored as NULL the value is not being stored pls suggest
Thanks
vijay
Related
I have the model below. I setup the unique constraint on the customer and the IP's in the table. I dont want to be able to add a new customer with the same name and/or ip's. If I attempt to do that, I expect SQLAlchemy to error out. Right now it is not, it is just allowing me to add multiple entries with the same IP and Customer name. My DB backend is SQLite
class SubInterfaces(db.Model):
__tablename__ = 'subinterfaces'
__table_args__ = (
db.UniqueConstraint('hub_wan1_public_ip', 'ip_transit', 'customer', 'neighbor_ip', name='unique_sub_interfaces'),
)
id = db.Column(db.Integer, primary_key=True)
carrier_vlan = db.Column(db.Integer)
cust_vlan_ipsec = db.Column(db.Integer)
cust_vlan_wan = db.Column(db.Integer)
hub_wan1_public_ip = db.Column(db.String)
ip_transit = db.Column(db.String)
neighbor_ip = db.Column(db.String)
user_account = db.Column(db.String)
customer = db.Column(db.String)
created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow())
status = db.Column(db.Integer)
location = db.Column(db.String)
is_primary = db.Column(db.Boolean)
#### Add customer piece ####
dict_to_add = {
"customer": request.json['customer'],
"hub_wan1_public_ip": request.json['HUB1_WAN1_PUBLIC_IP'],
"ip_transit": request.json['PRIMARY_TRANSIT'],
"location": request.json['LOCATION']
}
add_user = SubInterfaces(**dict_to_add)
db.session.add(add_user)
db.session.commit()
Not sure why the constrains are not working, but as a workaround I am doing a count on the DB and if more than 1, error out.
#first check if a customer exists, if it does error out
active_customer = response['customer']
count_customer = db.session.query(SubInterfaces).filter_by(customer=active_customer).count()
if (count_customer >= 1):
raise BadRequest(f"Customer {active_customer} already exists", 400, {'ext': 1})
I'm trying to re-start work for a previous project and Database server was deleted.
No database backup or SQL script. But schema is defined in Python Database Model.
Can I generate Database schema from it?
I have the following class defined:
class News(db.Model, AutoSerialize, Serializer):
__tablename__ = 'news'
news_id = Column(Integer, primary_key=True, server_default=text(
"nextval('news_news_id_seq'::regclass)"))
source = Column(String(64))
source_id = Column(String(64))
author = Column(String(128))
title = Column(String(256), nullable=False)
description = Column(String(65536))
url = Column(String(512))
url_to_image = Column(String(512))
published_at = Column(Date())
content = Column(String(65536))
campaign = Column(String(16))
score = Column(Float(53))
magnitude = Column(Float(53))
sentiment = Column(String(16))
rank_score = Column(Float(53))
rank_order = Column(Integer)
translated_content = Column(String(65536))
detected_language = Column(String(128))
inserted_at = Column(DateTime(True))
and
t_tags = Table(
'tags', metadata,
Column('tag_id', Integer, nullable=False,
server_default=text("nextval('tags_tag_id_seq'::regclass)")),
Column('tag_name', String(128), nullable=False)
)
When you have got the metadata and connection, you can just do
metadata.create_all(connection)
(I assume db.Model is a declarative base)
I have a "many to many" bidirectional, but when I create mapping data for Group and User, it's only working with 1 direction.
class Groups(db.Model):
__tablename__ = 'GROUPS'
grpid = db.Column(db.String, primary_key=True)
groups = db.relationship("GroupUsers", back_populates="profiles")
class Profiles(db.Model):
__tablename__ = 'PROFILES'
profileid = db.Column(db.String, primary_key=True)
profiles = db.relationship("GroupUsers", back_populates="groups")
class GroupUsers(db.Model):
__tablename__ = 'GRPUSERS'
autoid = db.Column(db.String)
brid = db.Column(db.String)
description = db.Column(db.String)
grpid = db.Column(db.String, db.ForeignKey("GROUPS.grpid"), primary_key=True)
profileid = db.Column(db.String, db.ForeignKey("PROFILES.tlid"), primary_key=True)
groups = db.relationship("Groups", back_populates="profiles")
profiles = db.relationship("Profiles", back_populates="groups")
# CREATE MAPPING
groups = Groups()
group = groups.get_by_grpid(grpid=grid)
profiles = Profiles()
profile = profiles.get_by_profileid(profileid=profileid)
groupuser = GroupUsers(autoid=GroupUsers.get_max_autoid(),brid=profile.brid)
# IT'S WORK. CAN CREATE PRIMARY KEY TO GRPUSERS
# groupuser.tlprofiles = profile
# group.profiles.append(groupuser)
# profile.save()
# IT ISN'T WORK WITH ERROR BELOW
groupuser.tlgroups = group
profile.groups.append(groupuser)
group.save()
When I create mapping from profile, it add primary key to GroupUser class, but when I create mapping from group, it can not create primary key for GroupUser class with error.
Can't update table GRPUSERS using NULL for primary key value on column GRPUSERS.profileid
I created a Table a Bmarks which has two foreign keys which have relation with same table Url_hash
class Hashed(Base):
__tablename__ = "url_hash"
hash_id = Column(Unicode(22), primary_key=True)
url = Column(UnicodeText)
clicks = Column(Integer, default=0)
def __init__(self, url):
cleaned_url = str(unidecode(url))
self.hash_id = unicode(generate_hash(cleaned_url))
self.url = url
class Bmark(Base):
__tablename__ = "bmarks"
bid = Column(Integer, autoincrement=True, primary_key=True)
hash_id = Column(Unicode(22), ForeignKey('url_hash.hash_id'))
clean_hash_id = Column(Unicode(22), ForeignKey('url_hash.hash_id'))
description = Column(UnicodeText())
extended = Column(UnicodeText())
stored = Column(DateTime, default=datetime.utcnow)
updated = Column(DateTime, onupdate=datetime.utcnow)
clicks = Column(Integer, default=0)
inserted_by = Column(Unicode(255))
username = Column(Unicode(255), ForeignKey('users.username'),
nullable=False,)
tag_str = Column(UnicodeText())
hashed = relation(Hashed,
foreign_keys="Bmark.hash_id",
backref="bmark",
uselist=False
)
clean_hashed = relation(Hashed,
foreign_keys="Bmark.clean_hash_id",
backref="bmark",
uselist=False
)
I am trying to store url after cleaning it a little bit like removing headers,utm parameters etc for indexing purposes
Error is occurring while creating the database
sqlalchemy.exc.ArgumentError: Error creating backref 'bmark' on relationship 'Bmark.clean_hashed': property of that name exists on mapper 'Mapper|Hashed|url_hash'
Actually the error message is very informative.
Just rename one of your backref="bmark" to something else like backref="my_clean_bmark".
I'm trying to batch delete objects from an association table by filtering on a column in one of the relationships. I use the following call in SQLAlchemy to make the delete
db.session.query(UserPaper).join(Paper, (UserPaper.paper_id ==
Paper.id)).filter(UserPaper.user_id == user.id).filter(Paper.journal_id
== journal.id).delete()
and it results in the following error
OperationalError: (OperationalError) (1054, "Unknown column 'papers.journal_id'
in 'where clause'") 'DELETE FROM userpapers WHERE userpapers.user_id = %s AND
papers.journal_id = %s' (1L, 1L)
Without the delete at the end, the SQLAlchemy query is
SELECT userpapers.user_id AS userpapers_user_id, userpapers.paper_id AS
userpapers_paper_id, userpapers.created AS userpapers_created,
userpapers.read_at AS userpapers_read_at, userpapers.score AS userpapers_score
FROM userpapers JOIN papers ON userpapers.paper_id = papers.id
WHERE userpapers.user_id = :user_id_1 AND papers.journal_id = :journal_id_1
which is correct. From the error I can see that when I append delete() to the query the join part of SQL statement gets lost and the database doesn't know how to find the papers.journal_id column obviously. What I don't understand is why does that happen?
This is the setup of my ORM objects
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
papers = db.relationship("UserPaper", backref=db.backref('users'), lazy='dynamic')
class Paper(db.Model):
__tablename__ = 'papers'
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(1024))
journal_id = db.Column(db.Integer, db.ForeignKey('journals.id'))
class UserPaper(db.Model):
__tablename__ = 'userpapers'
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True)
paper_id = db.Column(db.Integer, db.ForeignKey('papers.id'), primary_key=True)
paper = db.relationship("Paper", backref=db.backref('user_paper'))
read_at = db.Column(db.DateTime)
score = db.Column(db.Integer)
class Journal(db.Model):
__tablename__ = 'journals'
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(100), index = True, unique = True)
papers = db.relationship('Paper', backref = 'journal', lazy = 'dynamic')
I had the same problem with SQLALchemy 0.9 using MySQL 5.6. It looks like a bug/limitation. However, one better way to get arround (in comparison to creating the query, looping through the results and deleting them one by one) is to perform this task in two subsequent queries:
paperQuery = db.session.query(Paper.id)\
filter(Paper.journal_id == journal.id)
baseQuery = db.session.query(UserPaper)\
.filter(UserPaper.paper_id.in_(paperQuery.subquery()))
.filter(UserPaper.user_id == user.id).delete(synchronize_session='fetch')
It worked well for me, it should solve you issue too.