Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. #ORM-like to associate a User with a Post. Also, by enforcing the NOT NULL ability of the foreign key column, invalid numbers cannot be added.
  2.  
  3. from flask import Flask
  4. from flask_sqlalchemy import SQLAlchemy
  5. from datetime import datetime
  6.  
  7. app = Flask(__name__)
  8. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  9. app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
  10. db = SQLAlchemy(app)
  11.  
  12. class User(db.Model):
  13. id = db.Column(db.Integer, primary_key=True)
  14. username = db.Column(db.String(64), index=True, unique=True)
  15. email = db.Column(db.String(120), index=True, unique=True)
  16. password_hash = db.Column(db.String(128))
  17. posts = db.relationship('Post', lazy='dynamic', back_populates='author')
  18.  
  19. def __repr__(self):
  20. return '<User {}>'.format(self.username)
  21.  
  22. class Post(db.Model):
  23. id = db.Column(db.Integer, primary_key=True)
  24. body = db.Column(db.String(140))
  25. timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
  26. author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
  27. author = db.relationship('User')
  28.  
  29. def __repr__(self):
  30. return '<Post {}>'.format(self.body)
  31.  
  32. db.drop_all()
  33. db.create_all()
  34.  
  35. # Tony will be both created and added to the session
  36. u1 = User(username='tony', email='tony@example.com')
  37. db.session.add(u1)
  38.  
  39. # Jake will be created, but not added
  40. u2 = User(username='jake', email='jake@example.com')
  41.  
  42. # Create a post by Jake
  43. p1 = Post(body='this is my post!', author=u1)
  44.  
  45. # Add Tony's post to the session
  46. db.session.add(p1)
  47.  
  48. # Create a post by tony, since tony does not yet exist as a user, he is created automatically
  49. p2 = Post(body='this is my post!', author=u2)
  50.  
  51. # Add tony's post to the session
  52. db.session.add(p2)
  53.  
  54. # After the session has everything defined, commit it to the database
  55. db.session.commit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement