Advertisement
Guest User

models.py

a guest
Jul 14th, 2021
517
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1. # from flaskblog folder in __init__.py
  2. from enum import unique
  3. from datetime import datetime
  4. from app import db
  5. from sqlalchemy import Column, Integer, String
  6. from flask_login import UserMixin
  7. from flask_login import LoginManager
  8.  
  9. # https://stackoverflow.com/questions/63231163/what-is-the-usermixin-in-flask
  10.  
  11. # one to many relationship between both databases
  12.  
  13. class User(UserMixin, db.Model):
  14.     # The primary key creates the one in an one to many relationship between both databases
  15.     id = db.Column(db.Integer, primary_key=True)
  16.     username = db.Column(db.String(80), unique=True, nullable=False)
  17.     hashed_password = db.Column(db.String(128), nullable=False)
  18.     email = db.Column(db.String(120), unique=True, nullable=False)
  19.     # backref='user' connects to the user database. You name the backref= the same name as the database - the capital letter
  20.     # Connects Post database and User database through the posts variable
  21.     posts = db.relationship('Posts', backref='user', lazy=True)
  22.     # what does this do?
  23.     def __repr__(self):
  24.         return '<User %r>' % self.username
  25.  
  26.  
  27. class Posts(UserMixin, db.Model):
  28.     id = db.Column(db.Integer, primary_key=True)
  29.     title = db.Column(db.String(120), unique=True, nullable=False)
  30.     content = db.Column(db.String(120), unique=True, nullable=False)
  31.     date_posted = db.Column(db.DateTime, nullable=False,
  32.         default=datetime.utcnow)
  33.     # The foreign key creates the many in an one to many relationship between both databases
  34.     # user.id represents the id from the User database and the posts variable specifically backref='user'
  35.     user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
  36.     # what does this do?
  37.     def __repr__(self):
  38.         return '<Posts %r>' % self.username
  39.  
  40.  
  41. from app import login_manager
  42. # Use User.query.get instead of User.get because of sqlalchemy
  43. # what is user_id
  44. @login_manager.user_loader
  45. def load_user(user_id):
  46.    return User.query.get(user_id)
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement