Sqlalchemy - Insert into table if not exist in a column (Mysql) - sqlalchemy

I have a simple Table like this
class Employeecode(Base):
__tablename__ = 'employeecode'
id = Column(Integer, primary_key=True)
unique_code = Column(String(5), unique=True)
employe_name = Column(String(50))
designation = Column(String(50))
How i can create a function which will insert value into 'employeecode' table if 'unique_code' column doesn't have that value.
insert_unique(unique_code,employe_name,designation)

First you can store all previous unicode_value in a list and then you can check and run your query..
def function(**kwargs):
session = Session()
unique_list =[]
employeecodes = db.session.query(Employeecode).all()
for employee in employeecodes:
unique_list.append(employee.unique_code)
if kwargs['unique_code'] not in unique_list:
employee = Employeecode()
employee.unique_code = kwargs['unique_code']
employee.employe_name = kwargs['employe_name']
employee.designation = kwargs['designation']
session.commit()
retval = row2dict(employee)
session.close()
return retval
else:
pass

Related

Access/Query List of Object SQLAlchemy

I have a relationship that yields a list of objects
class Category(db.Model):
_id = db.Column("id", db.Integer, primary_key = True)
book_category = db.Column("book_category", db.String)
booklist = db.relationship('Books', backref = "book_category")
def __init__(self, book_category):
self.book_category = book_category
class Books(db.Model):
_id = db.Column("id", db.Integer, primary_key = True)
bookname = db.Column("bookname", db.String)
filename = db.Column("filename", db.String)
category = db.Column(db.Integer, db.ForeignKey('category.book_category'))
def __init__(self, bookname,filename):
self.bookname = bookname
self.filename = filename
So when I'm querying the category I have an access to category.booklist
Which would yield something like this
[<book1>, <book3>, <book4>]
I can access each using for loop however, I'm feeling that it is not the most efficient way to do.
Is there any way that I can do like
category.booklist.query.filter(books.bookname == variable).all()
Querying and filtering the list of objects yielded by category.booklist

How to make this query in sqlalchemy?

SELECT
maintener.*,
(SELECT COUNT(*)
FROM device d
WHERE d.in_stock_maintener_id = maintener.id) AS in_stock_devices
FROM maintener;
I'm creating a report that show all mainteners but i need to show the number of devices that each one of that mainteners has by looking at the devices model reference in_stock_maintener_id;
I have this models in my persist sqlalchemy.
class Maintener(persist.Base):
__tablename__ = 'maintener'
id = Column(Integer, primary_key=True)
name = Column(String(255))
document_number = Column(String(30))
phone_1 = Column(String(12))
phone_2 = Column(String(12))
email = Column(String(255))
class Device(persist.Base):
__tablename__ = 'device'
id = Column(Integer, primary_key=True)
serial = Column(String(45))
in_stock = Column(SmallInteger)
in_stock_maintener_id = Column(ForeignKey(u'maintener.id'), nullable=True, index=True)
in_stock_maintener = relationship(u'Maintener', lazy='noload', \
primaryjoin='Device.in_stock_maintener_id == Maintener.id')
If anyone could help me, i'll be grateful =)
sq = (
session
.query(func.count())
.select_from(Device)
.filter(Device.in_stock_maintener_id == Maintener.id)
).as_scalar()
q = session.query(Maintener, sq.label('in_stock_devices'))
Query above will return an enumerable of tuple(Maintener, Integer).
If you would like to have columns instead (as per your comment), then you can either specify the columns you want in the query implicitly:
q = session.query(Maintener.id, Maintener.name, sq.label('in_stock_devices'))
or if you would like all columns (as in SELECT *), then you could query the Table instead of the mapped entity:
q = session.query(Maintener.__table__, sq.label('in_stock_devices'))
Above I assumed that you use declarative extension.

SqlAlchemy Relationship and Marshmallow

I am trying to return JSON or even a complete string of a returned one to many sqlalchemy query. I am using Marshmallow at this point to try do it but it keeps returning incomplete data
I have two models defined as :
class UserModel(db.Model):
__tablename__ = 'usermodel'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
password = db.Column(db.String(120))
weekday = db.relationship('weekDay', cascade='all,delete-orphan', single_parent=True, backref=db.backref('usermodel', lazy='joined'))
class weekDay(db.Model):
__tablename__ = 'weekday'
id = db.Column(db.Integer, primary_key=True)
#Defining the Foreign Key on the Child Table
dayname = db.Column(db.String(15))
usermodel_id = db.Column(db.Integer, db.ForeignKey('usermodel.id'))
I have defined two schemas
class WeekdaySchema(Schema):
id = fields.Int(dump_only=True)
dayname = fields.Str()
class UserSchema(Schema):
id = fields.Int(dump_only=True)
username = fields.Str()
password = fields.Str()
weekday = fields.Nested(WeekdaySchema)
and finally I run the command (I pass the name in userName variable)
userlist = UserModel.query.filter_by(parentuser=userName).all()
full_schema = UserSchema(many=True)
result, errors = full_schema.dump(userlist)
print (result)
I print the result to see before I attempt to Jsonify it:
My weekday object is completely empty
'weekday': {}
Doesn anyone know how I can do this correctly
It's a one-to-many relationship and you must indicate it on UserSchema, like that
class UserSchema(Schema):
id = fields.Int(dump_only=True)
username = fields.Str()
password = fields.Str()
weekday = fields.Nested(WeekdaySchema, many=True)
read more on documentation

SQL alchemy query filter syntax is not working

Here are the models I am working with:
class User(db.Model):
__tablename__ = 'user'
uid = db.Column(db.Integer, primary_key=True, index=True)
firstName = db.Column(db.String(100))
lastName = db.Column(db.String(100))
emailAddress = db.Column(db.String(120), unique=True, index=True)
pwHash = db.Column(db.String(256))
userLevel = db.Column(db.Integer())
userAccountType = db.Column(db.Integer())
isUserActive = db.Column(db.Boolean())
isUserLockedOut = db.Column(db.Boolean())
userLastLogin = db.Column(db.DateTime())
lastInvalidLogin = db.Column(db.DateTime())
userCreatedAt = db.Column(db.DateTime())
userConfirmedAt = db.Column(db.DateTime())
userUpdatedAt = db.Column(db.DateTime(), onupdate=datetime.datetime.now())
userAddress = db.relationship('Address', backref='user', lazy='dynamic')
userContactMethod = db.relationship('UserContactMethod', backref='user', lazy='dynamic')
userSensor = db.relationship('Sensor', backref='user', lazy='dynamic')
userReading = db.relationship('Reading', backref='user', lazy='dynamic')
deliveryEvents = db.relationship('logSMTPDeliveryEvents', backref='user', lazy='dynamic')
class Reading(db.Model):
__tablename__ = 'reading'
rid = db.Column(db.Integer, primary_key=True)
uid = db.Column(db.Integer, db.ForeignKey('user.uid'))
sid = db.Column(db.Integer, db.ForeignKey('sensor.sid'))
readingTimestamp = db.Column(db.DateTime())
readingLightValue = db.Column(db.Integer)
readingLightStatus = db.Column(db.String(6))
readingTemp1 = db.Column(db.Float)
readingTemp2 = db.Column(db.Float)
readingHumidity = db.Column(db.Float)
So my table of readings has the User Id set as the foreign key in the readings table. Now when I try and issue a query like this:
queryResult = db.session.query(Reading).filter(Reading.uid == User.uid)
I get all the rows, which is incorrect. How should I be constructing this query?
Thanks!
C
It's not clear what you're trying to filter out from your question; Are you trying to find the Reading rows that correspond to a particular User row?
Supposing you have the email address of a user, and want to find the Reading's that belong to that user, you would need to build your query in three steps:
First, Start with a query that returns rows out of Reading:
q = session.query(Reading)
Next, extend the query to say that you want follow the user link to attributes of User.
q = q.join(Reading.user)
Finally Filter out only the rows that have the desired User features. Make sure you're filtering on a concrete, actual value.
q = q.filter(User.emailAddress == 'alice#example.com')

how to save data in a many to many relationship using turbogears and sqlalchemy

hi i have a many to many relationship between a user and a group.and i will like to add a user with many groups in my database.how do i do that if my database is as follows
user_group_table = Table('tg_user_group', metadata,
Column('user_id', Integer, ForeignKey('tg_user.user_id',
onupdate="CASCADE", ondelete="CASCADE")),
Column('group_id', Integer, ForeignKey('tg_group.group_id',
onupdate="CASCADE", ondelete="CASCADE"))
)
class Group(DeclarativeBase):
"""
Group definition for :mod:`repoze.what`.1
Only the ``group_name`` column is required by :mod:`repoze.what`.
"""
__tablename__ = 'tg_group'
#{ Columns
group_id = Column(Integer, autoincrement=True, primary_key=True)
group_name = Column(Unicode(16), unique=True, nullable=False)
display_name = Column(Unicode(255))
created = Column(DateTime, default=datetime.now)
#{ Relations
users = relation('User', secondary=user_group_table, backref='groups')
#{ Special methods
def __repr__(self):
return '<Group: name=%s>' % self.group_name
def __unicode__(self):
return self.group_name
#}
class User(DeclarativeBase):
"""
User definition.
This is the user definition used by :mod:`repoze.who`, which requires at
least the ``user_name`` column.
"""
__tablename__ = 'tg_user'
#{ Columns
user_id = Column(Integer, autoincrement=True, primary_key=True)
user_name = Column(Unicode(16), unique=True, nullable=False)
email_address = Column(Unicode(255), unique=True, nullable=False,
info={'rum': {'field':'Email'}})
display_name = Column(Unicode(255))
_password = Column('password', Unicode(80),
info={'rum': {'field':'Password'}})
created = Column(DateTime, default=datetime.now)
doing it this way however gives me an error
#expose()
def user_save(self, **kw):
user = User()
user.user_name = kw['user_name']
user.display_name = kw['display_name']
user.email_address = kw['Email']
user._password = kw['password']
user.groups.extend(kw['groups'])
DBSession.add(user)
DBSession.flush()
flash("successfully saved...")
flash(user)
redirect("/user_new")
pls help me solve this.thanks in advance
I believe the answer is in the error message that you havn't posted in the question. user.groups is a list of Group objects, while you assign a list of strings(?) got from form to it. Also I see no explicit DBSession.commit() call. Are you sure TurboGears will do it for you?