1

I have a function "GenerateUsername" which returns a random username. I use it in a manager in managers.py, but where would be the best place to have this function? In a separate file called helpers.py?

def GenerateUsername():
    username = str(random.randint(0,1000000))
    try:
        User.objects.get(username=username)
        return GenerateUsername()
    except User.DoesNotExist:
        return username;
4

1 回答 1

3

I think a more comprehensive answer is deserved here. There are several ways to go about it.

  1. utils.py for the whole django site: This has the flaw that all django apps in that site will dump their generic functions in here and this file would become a blob
  2. utils.py for each django app inside the site: So if you have two apps, app1 and app2, then you have app1/utils.py and app2/utils.py. This is slightly better than (1)
  3. Library outside of Django (maybe on the same level as Django): I often make libraries for generic Django APIs in case they may be used by more than 1 site. This has the additional advantage that if you launch a new Django site tomorrow, you could use this generic function in that site as well just by importing this library after having it on your path. Inside the library, you could have separate modules such as userutils.py, mailutils.py which will address the 'blob' issue and also organize your code better. I recommend this approach.
于 2013-06-06T13:32:12.093 回答