1

Sorry if the question is primitive. I am new to Flask and SQL Alchemy.

I have a model as below.

class Department(FlaskSerializeMixin,db.Model):
        id = db.Column(db.Integer, primary_key=True)
        dep_name = db.Column(db.String(100),unique=True,nullable=False)
        dep_prefix = db.Column(db.String(1),unique=True,nullable=False)
        cre_time =db.Column(db.DateTime)
        chg_time =db.Column(db.DateTime)

And I have route to edit the department as below

@menuOps_bp.route('/edit_dep', methods=['POST'])
def edit_dep():
    req=request.get_json()
    print(req)
    if Department.query.filter_by(id != req['row_id'], dep_name=req['deptName'] ).first() is None:
        if Department.query.filter_by(id != req['row_id'], dep_prefix=req['dPrefix'] ).first() is None:
            dep = Department.query.filter_by(id=req['row_id']).first()
            dep.dep_name=req['deptName']
            dep.dep_prefix=req['dPrefix']
            dep.chg_time = datetime.datetime.now()
            db.session.commit()
            return jsonify({'success':"Department {dep} is update succussfully".format(dep=req['deptName'])})
        else:
            return jsonify({'error' : " The PreFix [ {prefix} ] is already Used !!!".format(prefix=req['dPrefix'])})
    else:
        return jsonify({'error' :  " Department [ {dep} ] is already Used !!!".format(dep=req['deptName'])})

The app got sarted properly, but when calling the route with the if Department.query.filter_by(id != req['row_id'], dep_name=req['deptName'] ).first() is None: is failing with below error. Please help to resolve the issue.

  File "/home/rishthaz/QMS_AIMS/ECQ/ecqenv/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/rishthaz/QMS_AIMS/ECQ/v1/BE/menu/routes.py", line 29, in edit_dep
    if Department.query.filter_by(id != req['row_id'], dep_name=req['deptName'] ).first() is None:
**TypeError: filter_by() takes 1 positional argument but 2 were given**

basically I want to fire the query select count(1) from department where id != <somevalue> and dep_name = <somevalue>

1 Answers1

0

In your case, I would recommend using filter as opposed to filter_by, the reason being that you are aiming for comparison and not a keyword argument:

if not Department.query.filter(
         Department.id != req['row_id'], 
         Department.dep_name==req['deptName'] 
    ):
    ### continue...

filter accepts multiple arguments, and treats them as and in your case. Additionally you can also pass and_ or even call it twice:

if not Department.query\
    .filter(Department.id != req['row_id'])\
    .filter(Department.dep_name==req['deptName']):
    ### continue ...

Highly recommend this answer on the difference between filter and filter_by:

realr
  • 3,652
  • 6
  • 23
  • 34