0

I would like to know if there is a way to check if a row exists in the db, I'm working with an API and I'll be adding a script who will run every 24 hours to collect data from a page which has data from many companies, but if I run the script today and tomorrow for example there's a chance of gather almost the same data with new ones so I need to get rid of those, is a good idea to use COUNT or should I use if statements?

I'm adding this json data to my db:

{
OrgName: name,
Direction: Street 123
City: cityname
Lat: 13.123123
Lon: 12.123123
Code: XC23-123D
}

As mentioned before, the data can be repeated in all the keys but not in the code, will code=unique solve the problem?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Joaquín
  • 350
  • 2
  • 12
  • 1
    Upsert is the answer ! https://stackoverflow.com/questions/4069718/postgres-insert-if-does-not-exist-already – Bruck1701 Oct 27 '20 at 07:01
  • Thanks for the quick answer! I'll try it – Joaquín Oct 27 '20 at 07:03
  • hi, yes you need at least one field with `unique=True` in the model, and then you can filter if the object with that unique_field `exists()` or not. read django docs for this method – mh-firouzjah Oct 27 '20 at 07:08

1 Answers1

0

you can use

get_or_create(defaults=data)

when you want get data and set on db. visit django documentaion: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#get-or-create