Django: Import CSV file and handle clash of unique values correctly
Question: 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()
    


Answer: One of the Django orm function that i love so much is
[get_or_create()](http://www.djangoproject.com/documentation/models/get_or_create/)

so i will suggest you do like this:

    
    
    for row in dataReader:
        person_record, created = person.get_or_create(name=row[0], age=row[1])
    

you can check after if you want to change the old record in `person_record` or
check if the record was created `if created:` and do what ever you want with
it ..

hope this will help

