I wrote most of my web applications with Django frameworks. Recently I looked into Ruby on rails and found some interesting things. Like ModelObject.find_or_create_by_id()
Here is some Django code I have
try:
phone = request.POST.get('phone')
customer = Customer.objects.get(phone=phone)
updating customer...
except:
customer=Customer(
creating customer...
)
customer.save()
This piece of code looks ugly. Is there a better way to do this with Django ?
You can use
get_or_create:The second value (
created) is a boolean indicating if an existing object was retrieved or a new one created.Documentation:
https://docs.djangoproject.com/en/1.4/ref/models/querysets/#get-or-create