Python Forum
Inserting data from a table to another (in same db)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Inserting data from a table to another (in same db)
#1
Hello Everyone!
Would you kindly help figure out how to manage to carry out the following task. I have a database with two table, jobs (where there some data I'm interested in) and picks (where I'm looking to copy/insert data coming from jobs.
I'm working in Flask and Postgres, with my current code (below) I get error message: "Invalid syntax". Thank you for your help.
@app.route('/apply/<job_id>/', methods=['GET', 'POST'])
@login_required
def apply(job_id):
    for_listing = Job.query.get(job_id)
    applicant = session['username']
    date_applied = datetime.now()
    try:
        connection = psycopg2.connect(user="postgres",
                                  password="mypassword",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="jobapplied")
        cursor = connection.cursor()
        postgres_insert_query = INSERT INTO picks (for_listing, applicant, date_applied, jobname, jobdesc )
                                (SELECT job_name, job_desc, FROM jobs WHERE id = for_listing)
       
        cursor.execute(postgres_insert_query)
        connection.commit()
        flash ("Record inserted successfully into the picks table")
    except (Exception, psycopg2.Error) as error :
        if(connection):
            flash ("Failed to insert record into picks table", error)
    finally:
        #closing database connection.
        if(connection):
            cursor.close()
            connection.close()
Reply
#2
This is very poor design. why would you copy data from one table to another?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(Sep-28-2020, 05:31 AM)buran Wrote: This is very poor design. why would you copy data from one table to another?
Hi, thank you for your reply and your observation. I'm prototyping out a project that involves posting on a job board and job seekers selecting jobs. When a job seeker has chosen a job that job is to be saved in that job seeker's profile. Though there're probably others and better ways to do that, I thought of inserting in a table (a table associated with the job seeker) data coming from the job post table (having information of being selected by job seeker). The id of the job selected by the job seeker is obtain as follows:
#================in jinja2 template======================================
   {% if session.logged_in %}
          <a href="/apply/{{ job.id }}"><btn class="btn btn-primary">Apply</btn></a>
        {% endif %} 
#=======================in the route ===================================
@app.route('/apply/<job_id>/', methods=['GET', 'POST'])
@login_required
def apply_job(job_id):
    ...
    ...
#==========================in the model file===============================
class Job(db.Model):
    __tablename__ = 'jobs'  
    id = db.Column(db.Integer, primary_key=True)
    job_name = db.Column(db.Unicode)
    job_posted = db.Column(db.DateTime)
    category = db.Column(db.Unicode)
    job_desc = db.Column(db.Unicode)
    def __init__(self, job_name, job_posted, category, job_desc):
        self.job_name = job_name
        self.job_posted = job_posted
        self.category = category
        self.job_desc = job_desc
Reply
#4
In my opinion you should have
one table for advertised jobs, most likely linked to some other tables, e.g. departments
One table for applicants/job seekers. maybe linked to some other tables. Basically this will be their profile - name, contact info, etc.
One table where you will keep info about who interested in what job. One applicant may be interested in more than one job advertisement. Probably linked to other tables. In this table, as minimum you will have the id of the job, id of the participants and then may be some other info. no need to copy anything from jobs table - you will use JOINs to combine info from different tables
of course, variations are possible here and there, or slightly different approach
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
(Oct-03-2020, 05:02 PM)buran Wrote: In my opinion you should have
one table for advertised jobs, most likely linked to some other tables, e.g. departments
One table for applicants/job seekers. maybe linked to some other tables. Basically this will be their profile - name, contact info, etc.
One table where you will keep info about who interested in what job. One applicant may be interested in more than one job advertisement. Probably linked to other tables. In this table, as minimum you will have the id of the job, id of the participants and then may be some other info. no need to copy anything from jobs table - you will use JOINs to combine info from different tables
of course, variations are possible here and there, or slightly different approach
Hello, again thank you for your reply and continuing help. Trying to follow up on the suggestion you made I'm working out the following (the below)models. Please any constructive suggestion is welcome. Thank you.
class User(db.Model):#<----Parent table of the Applied class
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.Unicode)
    email = db.Column(db.Unicode)
    password = db.Column(db.Unicode)
    job_applied = db.relationship('Applied', backref='users')
    
    def __init__(self, username, email, password):
        self.username = username
        self.email = email
        self.password = password
        
class Job(db.Model):#<---How should I link this table to the other ones?
    __tablename__ = 'jobs'
    id = db.Column(db.Integer, primary_key=True)
    job_name = db.Column(db.Unicode)
    job_posted = db.Column(db.DateTime)
    category = db.Column(db.Unicode)
    job_desc = db.Column(db.Unicode)
    
    def __init__(self, job_name, job_posted, category, job_desc):
        self.job_name = job_name
        self.job_posted = job_posted
        self.category = category
        self.job_desc = job_desc

class Applied(db.Model):#<----Child table of User class, 
    __tablename__ = 'applications'
    id = db.Column('id', db.Integer, primary_key=True)
    date_applied = db.Column(db.DateTime)
    jobseeker_id = db.Column(db.Integer, db.ForeignKey('users.id'))

    def __init__(self, date_applied):
        self.date_applied = date_applied
Reply
#6
Not using sqlalchemy myslef, but I think in applications table you need one more field - job_id, to hold id of the job, linked to jobs table, the same way you link jobseeker_id to users

if you have users
1,John
2,Jane

in jobs

1,job1
2,job2

in applications you can have

id,jobseeker_id,job_id
1,1,1
2,2,1
3,1,2

For brevity I omit some of the columns, but basically John has applied for job1 and job2, while Jane has applied only for job1
So when someone apply - you insert their id and the id of the jon they applied for in applications table and that's it - no need to copy anything
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Scraping data from table into existing dataframe vincer58 1 2,008 Jan-09-2022, 05:15 PM
Last Post: vincer58
  Extract data from a table Bob_M 3 2,666 Aug-14-2020, 03:36 PM
Last Post: Bob_M
  Scraping a dynamic data-table in python through AJAX request filozofo 1 3,881 Aug-14-2020, 10:13 AM
Last Post: kashcode
  Table data with BeatifulSoup gerry84 11 7,194 Oct-23-2019, 10:09 AM
Last Post: Larz60+
  Want to scrape a table data and export it into CSV format tahir1990 9 5,244 Oct-22-2019, 08:03 AM
Last Post: buran
  Using flask to add data to sqlite3 table with PRIMARY KEY catafest 1 3,726 Sep-09-2019, 07:00 AM
Last Post: buran
  sqlalchemy DataTables::"No data available in table" when using self-joined table Asma 0 2,579 Nov-22-2018, 02:46 PM
Last Post: Asma
  Insert data in a table after a user is created from djando admin prithvi 0 3,538 Aug-11-2017, 06:25 PM
Last Post: prithvi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020