2021-07-30

SQL Alchemy check for duplicate records based on multiple values

I want to check for an existing row in my db instance based on attributes.

Here is my Model :

class BasketModel(Base):
    __tablename__ = 'basket'
    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
    org_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey('organization.id'))
    first_attribute = sqlalchemy.Column(sqlalchemy.String(2))
    second_attribute = sqlalchemy.Column(sqlalchemy.Integer)
    ... # many more attributes

In my relational model, a new record is considered as duplicated if all its non key attributes (excepted from id which is unique) are equals.

entityA = BasketModel(org_id=1, first_attribute="Hello", second_attribute="World")
entityB = BasketModel(org_id=1, first_attribute="Hello", second_attribute="World")
entityA == entityB # Should be True

Now if I want to add a new record I can simply do (thanks to ORM abstraction) :

session.add(entityA)

But if I want to check for an existing record based on values I have to check each single field (which is very ugly, not scallable and frustrating) :

# create entity A
entityA = BasketModel(org_id=1, first_attribute="Hello", second_attribute="World")

# add entity A 
session.add(entityA)
session.flush()
session.commit()

# Now A is in the Database

#create entity B
entityB = BasketModel(org_id=1, first_attribute="Hello", second_attribute="World")


# Check if any record exists with those attributes

session.query(BasketModel).filter(
                BasketModel.org_id == entityB.org_id,
                BasketModel.first_attribute == entityB.first_attribute,
                BasketModel.second_attribute == entityB.second_attribute,
                ... # and I have many more
                ).count()

This "works fine" because it output what I expected which is duplicated rows bases on values of each field. But it is pretty hard coded.

Is there any way to do something like this, that will check every non keys attributes and check for equality ? (It's weird that I did not found because I am pretty sure that each record is mapped to a kind of set behind the scene in the ORM...which occurrence could be "easily" checked ...

session.query(BasketModel).exists(entityB) # I did not find any API for that...


from Recent Questions - Stack Overflow https://ift.tt/3f7O3ps
https://ift.tt/eA8V8J

No comments:

Post a Comment