'having trouble make foreign id column point to already existing row flask python

So on the /join page, I am trying to add a person with an email to a team that is in the Team_name database that already exists. every time I try something it just creates a new row in the team_name column, but I want team_name_id of the name and email the person submits the /join page to point back to an already existing team in team_name column.

from distutils.command.sdist import sdist
from enum import unique
from turtle import back

from flask import Flask, redirect, render_template, session, url_for, request, flash
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from sqlalchemy import ForeignKey, select
from datetime import datetime
import sqlite3
from flask import g


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']= 'sqlite:///test.db'
db = SQLAlchemy(app)
#app.config['SQLALCHEMY_TRACK_MODIFICATIONS']= True
app.config['SECRET_KEY'] = 'sdafwer3rw93ur9wu0er339d'

class Forms(db.Model):
    __tablename__ = 'forms'
    id = db.Column(db.Integer, primary_key = True)
    names = db.Column(db.String(200), nullable = False)
    emails = db.Column(db.String(200))
    team_name_id = db.Column(db.Integer, db.ForeignKey('team_names.id'))
    
    def __repr__(self):
        return '<Forms %r>' % self.id
    
    def __init__(self, names, emails, team_names):
        self.names = names
        self.emails = emails
        self.team_names = team_names
        

        
class Team_names(db.Model):
    __tablename__ = 'team_names'
    id = db.Column(db.Integer, primary_key = True)
    team_name = db.Column(db.String(200), unique = True)
    formss = db.relationship('Forms', backref = 'team_names', lazy='dynamic')
    def __repr__(self):
        return '<Team_names %r>' % self.id

    def __init__(self, team_name):
        self.team_name = team_name
        
        
    

    


     
    


@app.route('/', methods=['POST','GET'])
def first():
    return render_template('first.html')

@app.route('/new', methods=['POST','GET'])
def new():
    if request.method == 'POST':
        givenname = request.form['names']
        givenemail = request.form['emails']
        giventeamnames = request.form['team_names']
        
        adding1 = Team_names(team_name = giventeamnames)
        adding = Forms(names = givenname, emails = givenemail, team_names=adding1) 
        
        
        try: 
            
            db.session.add(adding)
            db.session.add(adding1)
            db.session.commit()
            return render_template('thankyou.html')
        except: 
            return 'There was an error adding your team please try again or team name was not unique'
    else:
        return render_template('new.html')

@app.route('/join', methods=['POST','GET'])
def join():
   
    teams = Team_names.query.with_entities(Team_names.team_name)
    for team in teams:
       team = Team_names.team_name
    
    

    if request.method == 'POST':
    
        givennames = request.form['names']
        givenemails = request.form['emails']
        select = request.form('selected_class')
        adding1 = Team_names(team_name= select)
        adding = Forms(names = givennames, emails = givenemails, team_names=adding1 ) 
        
        try: 
            
            db.session.add(adding)
            db.session.commit()
            return render_template('thankyou.html')
        except:
            return str(print(select)) 
             #'There was an error join your team please try again'
    else:
        return render_template("join.html", teams=teams)

if __name__ == "__main__":
    app.run(debug=True)
<select id="team_names" name="selected_class" placeholder="Select your groups team name" class="text-box" required><br><br>
                {% for team in teams %}
                
                    <OPTION value={{team[0]}}>{{team[0]}}</OPTION>
                
                {% endfor %}</select><br><br>


Solution 1:[1]

Try this.

Replace:

adding1 = Team_names(team_name= select)
adding = Forms(names = givennames, emails = givenemails, team_names=adding1 ) 
        

with:

selected_team = db.session.query(Team_names).filter(Team_names.team_name == select).first()
adding = Forms(names = givennames, emails = givenemails, team_names = selected_team) 

In your original adding1 you are creating a new team based on the selected value. The proposed fix has SQLA grab a team object based on the selected value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mnzbono