سؤال

I want to insert several User rows in the DB. I don't really care if the insert didn't succeed, as long as I'm notified about it, which I'm able to do in both cases, so which one is better in terms of performance (speed mostly)?

  1. Always insert the row (by calling the model's save method) and catching potential IntegrityError exceptions
  2. Call the get_or_create method from the QuerySet class
هل كانت مفيدة؟

المحلول

Think about what are you doing: you want to insert rows into the database, you don't need to get the object out of it if it exists. Ask for forgiveness, and catch IntegrityError exception:

try:
    user = User(username=username)
    user.save()
except IntegrityError:
    print "Duplicate user"

This way you would avoid an overhead of an additional get() lookup made by get_or_create().

FYI, EAFP is a common practice/coding style in Python:

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements.

Also see: https://stackoverflow.com/questions/6092992/why-is-it-easier-to-ask-forgiveness-than-permission-in-python-but-not-in-java

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top