简体   繁体   中英

Sqlalchemy query/filter to check for duplicates on INSERT Python

I have a database of participants in a c

# ORM
class_students = db.Table(
    'class_students',
    db.Column('class_id', db.Integer(), db.ForeignKey('class.id')),
    db.Column('user_id', db.Integer(), db.ForeignKey('users.id')),
)

class Class(db.Model):
 id = db.Column(db.Integer)
 name=db.Column(db.String())

 students = db.relationship('User', secondary=class_students,
                            backref=db.backref('classes', lazy='dynamic'))

class User(db.Model):
 id = db.Column(db.Integer)
 username=db.Column(db.String())

Example

When creating a class, I would immediately add students to it, like this:

students_ids = [900,700,40]

new_class = Class()
db.session.add(new_class)
db.session.commit()

for id in students_ids:
    new_class.students.append(id)

The above is working fine but now I want to avoid duplicates when inserting students in a new class:

How do i check if this selected students are already in that Class?

Hi you can check if a student row exists in your db like this

exists = db.session.query(Student.id).filter_by(name=name).scalar() is not None

So you can check if the student exists by name or something. You can just replace name with your variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM