Friday, October 1, 2010

Re: A better way of checking if a record exists

For what it's worth, I use the get_or_create with the 'default' keyword to do this:

for record in reader:

new_values = {
'product_code': slugify(record['Product Code']),
'msrp': record['Suggested Retail'],
#etc...
}

product, was_created = Product.objects.get_or_create(source_id = record['Source ID'], defaults = new_values)

if not was_created:
product.product_code = slugify(record['Product Code'])
product.msrp = record['Suggested Retail']
#etc...
product.save()

I don't like the DRY violation, but a model instance doesn't have an update() method like a queryset for me to dump the kwargs into -- unless I'm missing something.

Shawn


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment