I want to write a Python script to import the contents of CSV file into a Django app's database. So for each CSV record, I create an instance of my model, set the appropriate values from the parsed CSV line and call save on the model instance. For example, see below:
for row in dataReader:
person=Person()
person.name=row[0]
person.age=row[1]
person.save()
Now, lets say that the name Field is marked as unique in the Model. What's the best way to handle the situation where the record being imported has the same Name value as one already in the database? Should I check for this before calling save? How? Should I catch an exception? What would the code look like?
EDIT: If a record already exists in the db with the same name field, I would still like to update the other fields. For example, if I was importing Fred,43 and there was already a record Fred,42 in the db it should update the db to Fred,43.
EDIT: Thanks for all the answers. This approach, pointed to by chefsmart, is the one I think I will go with:
try:
obj = Person.objects.get(name=name)
except Person.DoesNotExist:
obj = Person()
obj.name = name
obj.age = age
obj.save()