Hi my table named ‘total’ looks like this,
JavaScript
x
2
1
{id:1,alias:tiger,status:gold}
2
If I want to insert a new row with a new alias lets say alias = ‘lion’ and status = ‘gold’ it should create a new id and the table should look like this
JavaScript
1
3
1
{id:1,alias:tiger,status:gold}
2
{id:2,alias:lion,status:gold}
3
But if I keep the alias same as ‘lion’ and status = ‘silver’ it should just update the row with id = 2 and it should look like this
JavaScript
1
3
1
{id:1,alias:tiger,status:gold}
2
{id:2,alias:lion,status:silver}
3
How to achieve it in sqlalchemy using insert command?
the id is primary key and alias value is stored in a variable a and status value is stored in a variable b, which looks like
JavaScript
1
2
1
a = 'lion', b= 'gold'
2
Advertisement
Answer
Looks like your alias
is unique identifier for the object/row. In this case an approach of find-and-update OR create
should work:
JavaScript
1
14
14
1
a = 'lion'
2
b = 'gold'
3
4
# find the object (by `alias`) in the database
5
obj = session.query(Total).filter(Total.alias == a).first()
6
if obj:
7
# object found: update the status
8
obj.status = b
9
else:
10
# object not found: create and add to the session
11
obj = Total(alias=a, status=b)
12
session.add(obj)
13
session.commit()
14
See documentation: