joshlsullivan
joshlsullivan

Reputation: 1500

Remove duplicates from SQLAlchemy query using set

I have a lot of duplicates in the database. To only deliver one (instead of duplicates), I'm trying to use set, but it is returning the duplicates too.

all_orders = Order.query.filter_by(account_id=account.id).all()
orders = set(all_orders)
{377, 348, 353, 377, 354, 377, 356, 377, 357, 377, 359, 378, 358, 378, 361, 378, 357, 378, 364, 378, 363, 378, 378, 362, 364, 379, 355, 379, 366, 379, 367, 379, 368, 379, 358, 379, 369, 379, 358, 379, 369, 379, 337, 370, 379, 338, 370, 379, 339, 343, 371, 379, 347, 371, 379, 372, 379, 372, 379, 373, 379, 373, 379, 374, 379, 374, 379, 375, 379, 375, 379, 376, 379, 376, 379, 376, 379, 376, 379, 376, 379, 377, 379, 377, 379, 377, 379, 377, 379, 377, 380, 377, 381, 377, 377, 377, 377}

EDIT

I am receiving webhook data, and the webhook fired multiple times. I was able to set the sale_id to unique, preventing duplicate data from occurring any further.

Upvotes: 1

Views: 15559

Answers (1)

Dash Winterson
Dash Winterson

Reputation: 1295

Use the .distinct() method in your sql alchemy query to get a set-like list.

 ...
 timestamp = calendar.timegm(created.utctimetuple()) # Used to convert time for Intercom   
 orders = Order.query.filter_by(account_id=account.id).distinct()
 print(orders)
 ...

Upvotes: 7

Related Questions