You need get_or_create
:
car,created = Car.objects.get_or_create(slug='car-slug')
if created:
print 'New car was created'
car.slug = 'new-car-slug'
else:
# do whatever needs to be done here
# with the existing car object, which will
# be car
# car.name = 'new name'
car.save()
Whatever arguments you provide to get_or_create
, it will use those to search existing records for the model.
Suppose you don't know what combination of fields will trigger a duplicate. The easy way is to find out which fields in your model have that restriction (ie unique=True
). You can introspect this information from your model, or a simpler way is to simply pass these fields to get_or_create
.
First step is to create a mapping between your XML fields and your model's fields:
xml_lookup = {}
xml_lookup = {'CAR-SLUG': 'slug'} # etc. etc.
You can populate this will all fields if you want, but my suggestion is to populate it only with those fields that have a unique constraint on them.
Next, while you are parsing your XML, populate a dictionary for each record, mapping each field:
for row in xml_file:
lookup_dict = {}
lookup_dict[xml_lookup[row['tag']] = row['value'] # Or something similar
car, created = Car.objects.get_or_create(**lookup_dict)
if created:
# Nothing matched, a new record was created
# Any any logic you need here
else:
# Existing record matched the search parameters
# Change/update whatever field to prevent the IntegrityError
car.model_slug = row['MODEL_SLUG']
# Set/update fields as required
car.save() # Save the modified object