I am learning Flask and I want to create a database which contains 3 tables which are related between them:
- Company: info about the company I worked for (made up :) )
- Job: info about the role I had in each company
- Task: info about the tasks i had in each job i had in each company.
Here is the code:
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///work_experience.db'
db = SQLAlchemy(app)
class Company(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
start_date = db.Column(db.DateTime, nullable=False)
end_date = db.Column(db.DateTime, nullable=False, default=None)
location = db.Column(db.String(20), nullable=False, default='N/A')
jobs = db.relationship('Job', backref='company_')
class Job(db.Model):
id = db.Column(db.Integer, primary_key=True)
position = db.Column(db.String(100), nullable=False)
start_date = db.Column(db.DateTime, nullable=False)
end_date = db.Column(db.DateTime, nullable=False)
company_id = db.Column(db.Integer, db.ForeignKey('company.id'))
tasks = db.relationship('Task', backref='job_')
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
description = db.Column(db.String(100), nullable=False)
start_date = db.Column(db.DateTime, nullable=False)
end_date = db.Column(db.DateTime, nullable=False)
job_id = db.Column(db.Integer, db.ForeignKey('job.id'))
db.create_all()
My I idea is to have a for loop (which eventualy I will write with Jinja2, but for now python code is fine) in such a way that I can print for each company the job that I had and what task I accomplished. Of course I could have all the data in just one table but I am trying to learn.
Therefore the output should be something like this:
for company in Companies:
for job in Jobs:
for Task in Tasks:
print(company, job, task)
Can you suggest me a smart and elegant way to achieve my goal? Thanks in advance.