llazzaro
llazzaro

Reputation: 4188

Django : proper way to use model, duplicates!

I have a question about the proper, best way to manage the model. I am relative newbie to django, so I think I need to read more docs, tutorials,etc (suggestions for this would be cool!).

Anyway, this is my question :

I have a python web crawler, that is "connected" with django model.

Crawling is done once a day, so its really common to find "duplicates". To avoid duplicates I do this :

cars = Car.Objects.filter(name=crawledItem['name'])
if len(cars) > 0:
    #object already exists, update it
    car = cars[0]
else:
    car = Car()

#some non-relevant code here

car.save()

I want to know, if this is the proper/correct way to do it or its any "automatic" way to do it.

Its possible to put the logic inside the Car() constructor also, should I do that?

Thanks a lot!

Upvotes: 0

Views: 206

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

Use the get_or_create() method of the manager, then modify the returned instance as needed.

Upvotes: 6

Related Questions