I am trying to get the price value from my EVENTS class as an INT so that I can use it to make a booking by multiplying by the number of attendees for an event when I insert a new row in the booking table.
Tables in databse
class Event(db.Model):
__tablename__ = 'events'
id = db.Column(db.Integer, primary_key=True)
host = db.Column(db.String(80), nullable=False)
event_title = db.Column(db.String(80), nullable=False)
event_description = db.Column(db.String(80), nullable=False)
movie_name = db.Column(db.String(80), nullable=False)
movie_description = db.Column(db.String(80), nullable=False)
genre = db.Column(db.String(80), nullable=False)
movie_start_time = db.Column(db.Time(), nullable=False)
movie_end_time = db.Column(db.Time(), nullable=False)
classification = db.Column(db.String(80), nullable=False)
rating = db.Column(db.Integer(), nullable=False)
actors = db.Column(db.String(200), nullable=False)
directors = db.Column(db.String(200), nullable=False)
event_date = db.Column(db.Date(), nullable=False)
published_date = db.Column(db.Date(), nullable=False)
published_by = db.Column(db.String(80), nullable=False)
image = db.Column(db.String(60), nullable=False)
capacity = db.Column(db.Integer(), nullable=False)
address = db.Column(db.String(80), nullable=False)
status = db.Column(db.String(80), nullable=False)
price = db.Column(db.Integer(), nullable=False)
# ... Create the Comments db.relationship
# relation to call destination.comments and comment.destination
comments = db.relationship('Comment', backref='event')
class Booking(db.Model):
__tablename__ = 'bookings'
id = db.Column(db.Integer, primary_key=True, unique=True)
attendees = db.Column(db.Integer(), nullable=False)
total_price = db.Column(db.Integer(), nullable=False)
booked_at = db.Column(db.DateTime, default=datetime.now())
# foreign key
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
event_id = db.Column(db.Integer, db.ForeignKey('events.id'))
Code calling from Events table to get price and insert new row into Booking table
price = Event.query.with_entities(Event.price).filter_by(id = event)
user_name = User.query.with_entities(User.id).filter_by(name = current_user.name)
num_attendees = forms.attendees.data
print(num_attendees)
print(type(price))
booking = Booking(attendees=forms.attendees.data,
total_price= price * num_attendees,
user_id = user_name,
event_id = event)
#here the back-referencing works - comment.destination is set
# and the link is created
db.session.add(booking)
db.session.commit()
But I keep running into errors such as TypeError: unsupported operand type(s) for *: 'Row' and 'int'
Thank you
Related
class actionsModel(db.Model):
__tablename__ = 'actions'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
time = db.Column(db.DateTime, default=datetime.now())
symbol = db.Column(db.String(10), db.ForeignKey('stocks.symbol'), nullable=False)
direction = db.Column(db.Integer,nullable=False)
amount = db.Column(db.Float, nullable=True)
_amount = db.Column(db.Float, nullable=True)
price = db.Column(db.Float, nullable=False)
trade_price = db.Column(db.Float, nullable=True)
trade_amount = db.Column(db.Float, nullable=True)
status = db.Column(db.Integer, default=1)
result = db.Column(db.String(200), default=1)
count = db.Column(db.Integer, default=0)
position = db.Column(db.Integer, default=0)
entrust_no = db.Column(db.String(20), nullable=True)
renew = db.Column(db.Boolean, default=0)
strategy_id = db.Column(db.Integer,db.ForeignKey('strategy.id'))
account_id = db.Column(db.Integer, db.ForeignKey('accounts.id'))
strategy = db.relationship('strategyModel', backref=db.backref('actions'))
account = db.relationship('accountsModel', backref=db.backref('actions'))
stock = db.relationship('stocksModel', backref=db.backref('actions'))
actions_info = actionsModel.query.join(stocksModel).filter(actionsModel.time > date_start).with_entities(
actionsModel.symbol,
func.count('*').label('count'),
func.count(func.IF(actionsModel.direction == 'sell',1,None)).label('sell_count'),
func.count(func.IF(actionsModel.direction == 'buy', 1, None)).label('buy_count'),
).group_by(actionsModel.symbol).all()
date_start is a self-defined datetime value.
i have got sell_count and buy_count using the method below.
now i want to add a new field named 'trade_times' which equal the smaller one between sell_count and buy count.
how can i get trade_times within 'with_entities'?
I am creating a site where you can log in and then add your favorite animes and movies to your favorite list, for that I created a database and 3 tables User, Anime and Movie.
My database code:
from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(150), unique=True)
password = db.Column(db.String(150))
first_name = db.Column(db.String(150))
anime = db.relationship('Anime')
movie = db.relationship('Movie')
class Movie(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50), nullable=False)
date = db.Column(db.DateTime(timezone=True), default=func.now())
year = db.Column(db.Integer, nullable=False)
description = db.Column(db.String(400), nullable=False)
rating = db.Column(db.Float, nullable=True)
ranking = db.Column(db.Integer, nullable=True)
review = db.Column(db.String(50), nullable=True)
img_url = db.Column(db.String(250), nullable=False)
movie_link = db.Column(db.String(250), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
class Anime(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50), nullable=False)
year = db.Column(db.Integer, nullable=False)
date = db.Column(db.DateTime(timezone=True), default=func.now())
description = db.Column(db.String(400), nullable=False)
rating = db.Column(db.Float, nullable=True)
ranking = db.Column(db.Integer, nullable=True)
review = db.Column(db.String(50), nullable=True)
img_url = db.Column(db.String(250), nullable=False)
anime_link = db.Column(db.String(250), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
I want to first filter all the data with the current user id
(all_anime = Anime.query.filter_by(id=current_user.id.).all())
then sort them according to the ratings given by the user
(all_anime = Anime.query.order_by(Anime.rating).all())
all_anime = User.anime.query.order_by(Anime.rating).all()
all_anime = db.session.query(Anime).filter_by(id=current_user.id).all()
print(all_anime)
for i in range(len(all_anime)):
all_anime[i].ranking = len(all_anime) - i
db.session.commit()
I know this snippet of code is wrong but I want to perform two different functions in two different columns how can I do it.
I also wanted to not accept the anime titles which are already present in the list of that user.
for that purpose, I have to filter the data with that user id
(anime_name = Anime.query.filter_by(id=current_user.id).all())
and then filter the data with the anime title
(anime_name = Anime.query.filter_by(title=data['canonicalTitle']).first()))
#views.route("/anime/find")
def find_anime():
anime_api_id = request.args.get("id")
if anime_api_id:
movie_api_url = f"https://kitsu.io/api/edge/anime//{anime_api_id}"
response = requests.get(movie_api_url)
data = response.json()['data']['attributes']
name = data["canonicalTitle"].replace(' ', '%20')
description = data['description'].rsplit('.', 1)[0]
# anime_name = User.anime.query.filter_by(title=data['canonicalTitle']).first()
# if anime_name:
# flash("Anime Already exists In The List.", category="error")
# else:
new_anime = Anime(
title=data['canonicalTitle'],
year=data['startDate'].split("-")[0],
img_url=data['posterImage']['medium'],
description=description,
anime_link=ANIME_SEARCH + name,
user_id=current_user.id
)
db.session.add(new_anime)
db.session.commit()
flash("Successfully Added.", category="success")
return redirect(url_for("views.edit_anime", id=new_anime.id))
I have the following database model:
#login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(20), unique=True, nullable=False)
password = db.Column(db.String(30), nullable=False)
email = db.Column(db.String(100), nullable=False, unique=True)
adverts = db.relationship('Advert', backref='autor', lazy=True)
messages_sent = db.relationship('Message',foreign_keys='Message.sender_id', backref='author', lazy='dynamic')
messages_received = db.relationship('Message',foreign_keys='Message.recipient_id', backref='recipient', lazy='dynamic')
telephone = db.Column(db.String(15))
def __repr__(self):
return f"User('{self.username}', '{self.email}'"
class Advert(db.Model):
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.DateTime, nullable=False, default = datetime.utcnow)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable = False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
category = db.Column(db.String(50), nullable=False)
price = db.Column(db.Integer)
city = db.Column(db.String(), nullable=False)
messages = db.relationship('Message', backref='messages', lazy=True)
def __repr__(self):
return f"Advert('{self.title}', '{self.date}', '{self.category}')"
class Message(db.Model):
id = db.Column(db.Integer, primary_key=True)
sender_id = db.Column(db.Integer, db.ForeignKey('user.id'))
recipient_id = db.Column(db.Integer, db.ForeignKey('user.id'))
title = db.Column(db.String(100), nullable=False)
body = db.Column(db.String(300), nullable=False)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
ad_title = db.relationship('Advert', foreign_keys='Advert.title', backref='adtitle', lazy='dynamic')
def __repr__(self):
return f"Message('{self.body}')"
but the relationship between Message and Advert tables doesn't work. I want to do that the every Message have refer to Advert title. Anyone know the solution for this problem?
model:
'''任务工单'''
__tablename__ = 'task'
id = db.Column(db.Integer, primary_key=True, nullable=False, autoincrement=True)
user_id = db.Column(db.Integer, index=True, nullable=False)
dep_id = db.Column(db.Integer, index=True, nullable=False)
title = db.Column(db.String(200), nullable=False, index=True)
content = db.Column(db.Text, nullable=False)
cate = db.Column(db.SmallInteger, default=1,`enter code here`)
add_time = db.Column(db.Integer, default=int(time.time()), comment="添加时间")
is_top = db.Column(db.SmallInteger, default=0, comment="是否加急 1--加急 0--不加急")
desgin_id = db.Column(db.Integer,comment="设计人员的id")
update_time = db.Column(db.Integer, comment="修改时间")
review_time = db.Column(db.Integer, comment="审核时间")
assignment_time = db.Column(db.Integer, comment='分配时间')
fiannce_time = db.Column(db.Integer, comment='完成时间')
invalid_time = db.Column(db.Integer, comment='无效时间')
desgin_time = db.Column(db.Integer, comment="开始设计时间")
state = db.Column(db.SmallInteger, default=1, comment="状态:1--初始化待分配 2--带设计 3--设计中 4--提交待审核(审核中) 5--驳回 7--完成 0--无效")
use:
taskDicts = Task.query.filter_by(state=state).order_by(desc(Task.is_top),asc(Task.add_time)).offset(offset).limit(10).all()
venv/lib/python3.7/site-packages/sqlalchemy/orm/loading.py:246:
SAWarning: fully NULL primary key identity cannot load any object.
This condition may raise an error in a future release.
I have got two tables:
Announcements
AnnouncementsSchedule
Relationship is one(Announcements) to many(AnnouncementsSchedule) by keys:
Announcements.id = AnnouncementsSchedule.announcements_id
I tried to describe models in SQLAlchemy:
The first table is described as model:
class Announcements(db.Model):
__tablename__ = 'announcements'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(150), nullable=False)
text = db.Column(db.Text(), nullable=False)
category = db.Column(db.Integer(), nullable=False)
subcategory = db.Column(db.Integer(), nullable=False)
offer_type = db.Column(db.Integer(), nullable=False)
url = db.Column(db.String(150), nullable=True)
status = db.Column(db.Integer(), nullable=False)
#children = relationship("AnnouncementsSchedule", back_populates="announcements")
Second is:
class AnnouncementsSchedule(db.Model):
__tablename__ = 'announcements_schedule'
id = Column(Integer, primary_key=True)
week_day = db.Column(db.Integer(), nullable=True)
week_all = db.Column(db.Integer(), nullable=False)
time = db.Column(db.Time(), nullable=False)
announcement_id = Column(Integer, ForeignKey('announcements.announcements_id'))
What I do wrong?
You have a mistake in the column name (announcements doesn't have announcement_id ):
# announcement_id = Column(Integer, ForeignKey('announcements.announcements_id'))
# change to ->
announcement_id = Column(Integer, ForeignKey('announcements.id'))