users model
class User(db.Model):
__tablename__ = "users"
id = db.Column('user_id',db.Integer , primary_key=True)
username = db.Column('username', db.String(20), unique=True , index=True)
password = db.Column('password' , db.String(250))
posts = db.relationship('Post', backref = 'user', lazy = 'dynamic')
def __init__(self , username ,password ):
self.username = username
self.password = password
posts model
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(140))
text = db.Column(db.String(2000))
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'))
def __init__(self, title, text):
self.title = title
self.text = text
now I want to add comments model but dont know how to do it .please help me in comments view also .
comments should be connected to user and post .
Thank You
I solved this myself
here is the comments model
class Comment(db.Model):
__tablename__ = 'comments'
id = db.Column(db.Integer, primary_key = True)
text = db.Column(db.String(2000))
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'))
post_id = db.Column(db.Integer, db.ForeignKey('posts.post_id'))
def __init__(self, text):
self.text = text
Related
I have created the model below to store user and profile data separately in my database
class User(db.Model):
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(40), unique=True)
password = db.Column(db.String(255))
profile = db.relationship('Profile', backref='Profile', uselist=False)
class Profile(db.Model):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(25))
last_name = db.Column(db.String(25))
email = db.Column(db.String(25), unique=True)
phone_number = db.Column(db.String(25), unique=True)
post_code = db.Column(db.String(25))
house_number = db.Column(db.String(25))
user = db.Column(db.Integer, db.ForeignKey('user.id'))
I have attempted to populate Profile Model via this method, however, it does not work.
#routes.route('/register', methods = ['POST'])
def register():
if request.method == 'POST':
data = request.get_json()
new_user = User(username = data['username'], password = data['password'])
new_user.profile.first_name = data['first_name']
new_user.profile.last_name = data['last_name']
new_user.profile.email = data['email']
new_user.profile.phone_number = data['phone_number']
new_user.profile.post_code = data['post_code']
new_user.profile.house_number = data['house_number']
db.session.add(new_user)
db.session.commit()
return {'msg' : 'sucess'}
I get this error, would you please explain what I am doing wrong? I noticed that User.profile column is not present inside my database, however, I thought that was normal for a ForiegnKey?
File "C:\routes\register.py", line 11, in register
new_user.profile.first_name = data['first_name']
AttributeError: 'NoneType' object has no attribute 'first_name'
What is the solution ? I am assuming I need to create Profile() model separately but how do I simultaneously link that to an uncommitted User() model?
A few ways to do this, but you probably want to create an __init__(...) for user where you initialize a Profile object.
Something like this...
class User(db.Model):
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(40), unique=True)
password = db.Column(db.String(255))
profile = db.relationship('Profile', backref='Profile', uselist=False)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.profile = Profile()
I have defined two model with relation between them as below:
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(40), nullable=False, unique=False)
db.relationship('User', backref='role', lazy='dynamic')
def __init__(self, name):
self.name = name
def __repr__(self):
return f'<Role id={self.id} name={self.name}>'
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(40), unique=True)
password = db.Column(db.String(40), unique=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
def __init__(self, username, password, role_id):
self.username = username
self.password = password
self.role_id = role_id
def __repr__(self):
return f'<User id={self.id} username={self.username} password={self.password}>'
Then inside shell I created entries as below:
> admin_role = Role('Admin')
> db.session.add(admin_role)
> db.session.commit()
> admin_user = User('adminusername', 'adminpassword',admin_role.id)
> db.session.add(admin_user)
> db.session.commit()
When I try to query model I get perfect result:
>>> admin_role = Role.query.first()
>>> admin_user = User.query.first()
>>> print(admin_role)
<Role id=1 name=Admin>
>>> print(admin_user)
<User id=1 username=adminusername password=adminpassword>
But when I try to access relation
print(admin_role.users)
print(admin_user.role)
I get errors Role object has no attribute users and User object has no attribute role respectively.
Typo? You have to assign db.relationship() instance to a variable.
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(40), nullable=False, unique=False)
- db.relationship('User', backref='role', lazy='dynamic')
+ users = db.relationship('User', backref='role', lazy='dynamic')
I have trouble linking two tables with 'Posts' and 'Comments' so comments are only displayed on particular post, where they have been created.
With linking post and user I used current_user.id to make link between tables, but using ForeignKey gaves me always error:
sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Post.post_rel - there are no foreign keys linking these tables
Below is my code:
class Post(db.Model):
__tablename__ = 'post'
id = db.Column(Integer, primary_key=True)
title = db.Column(String(50))
subtitle = db.Column(String(50))
author = db.Column(String(20))
date_posted = db.Column(DateTime)
content = db.Column(Text)
post_rel = relationship('Post', back_populates='comment_rel', foreign_keys='[Comment.post_id]')
def get_comments(self):
return Comments.query.filter_by(post_id=post.id).order_by(Comments.timestamp.desc())
def __repr__(self):
return '<Post %r>' % (self.body)
class Comment(db.Model):
__tablename__ = 'comment'
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.String(140))
author = db.Column(db.String(32))
timestamp = db.Column(db.DateTime(), default=datetime.utcnow, index=True)
post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
comment_rel = relationship('Comment', uselist=False, back_populates='post_rel')
def __init__(self, text, author, timestamp):
""""""
self.text = text
self.author = author
self.timestamp = timestamp
def __repr__(self):
return '<Post %r>' % (self.body)
def show(self):
return self.author + '\n' + self.text
In your relationship, you have to change the name of the tables.
post_rel = relationship('Comment', back_populates='comment_rel',
foreign_keys='[Comment.post_id]')
comment_rel = relationship('Post', uselist=False,
back_populates='post_rel')
I have corrected your code:
BaseModel = declarative_base()
class Post(BaseModel):
__tablename__ = 'post'
id = Column(Integer, primary_key=True)
title = Column(String(50))
subtitle = Column(String(50))
author = Column(String(20))
post_rel = relationship('Comment', back_populates='comment_rel', foreign_keys='[Comment.post_id]')
class Comment(BaseModel):
__tablename__ = 'comment'
id = Column(Integer, primary_key=True)
text = Column(String(140))
author = Column(String(32))
comment_rel = relationship('Post', uselist=False, back_populates='post_rel')
This is my code:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////root/Desktop/Social_Network/users.db'
app.config['SQLALCHEMY_BINDS'] = {'posts': 'sqlite:////root/Desktop/Social_Network/posts.db'}
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(40), unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
joined_at = db.Column(db.DateTime(),default =datetime.datetime.now)
is_hero = db.Column(db.Boolean(),default=False)
class Post(db.Model):
__bind_key__ = 'posts'
id = db.Column(db.Integer, primary_key=True)
user = db.Column(db.String(50))
post = db.Column(db.String(255))
score = db.Column(db.Integer, nullable=False)
downVotes = db.Column(db.Integer, nullable=False )
posted_time = db.Column(db.DateTime(),default =datetime.datetime.now)
upVotes = db.Column(db.Integer,nullable=False)
dict_ = {}
def get_all_users():
users_ = User.query.all()
global dict_
for user in users_:
dict_[user.email] = user.password
return dict_
I have connected multiple databases in SQLAlchemy. My problem is whenever I run :
users_ = User.query.all()
. It returns the User object, but after I run the change it to post, something like this:
post = Post.query.all()
It returns none. Any help regarding this issue?
Using Flask-SQLAlchemy I have a table which looks like this:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
slug = db.Column(db.String(200), nullable=False)
def __init__(self, name):
self.name = name
I have a Python library which converts the value of some text into a slug like slugify('Hello World') to hello-world.
Say I was to create a User:
user = User('John Smith')
db.session.add(user)
db.session.commit()
I would like the value of slug in the User table to be Slugify('John Smith').
How would I go about this? Thanks.
As IanAuld said in the comments I should just add self.slug = slugify(name) like so:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
slug = db.Column(db.String(200), nullable=False)
def __init__(self, name):
self.name = name
self.slug = slugify(name)