简体   繁体   中英

More Pythonic/Django-esque way to write this?

Is there a more elegant way to write this?

    try: 
        author = Author.objects.get \
                      (internal_id=line[5])
    except: 
        author = Author.objects.get \
                      (internal_id=author_mapper[line[5]]) 

Or is this the best there is?

author_id = line[5]
try: 
    author = Author.objects.get(internal_id=author_id)
except Author.DoesNotExist: #blank excepts are bad and hide errors.
    author_id = author_mapper[line[5]]
    author = Author.objects.get(internal_id=author_id) 

Your version was good enough for jazz. However, you should add an explicit exception to catch, as a blank except statement can be rather dangerous. Imagine a situation where using internal_id=line[5] raises Author.MultipleItemsReturned . You definatly want this to raise, and/or deal with it seperatly, as it is a very different problem that could have been hidden. Ok, in this case it probabaly wouldn't have been, but just in general, blank except s aren't good :)

IMO, this reads better:

author_id = line[3]
alternate_id = author_mapper[author_id]
query = Author.filter(internal_id = author_id)
alternate_query = Author.filter(internal_id = alternate_id)
query = query or alternate_query
author = query[0]

Some notes: you should be able to guarantee that these internal ids are unique (this is safe to assume since you're using the get method). The alternate query will not be executed as long as the first query has results. Further improvement might be to make a method return query and alternate query. You could then not even make a query instance (these are fairly cheap, but if you're really looking for light and clean...)

Example:

author_id = line[5]
query = RegularQuery(author_id) or AlternateQuery(author_id, author_mapper)
author = query[0]

In case anyone is foggy on what is going on, when two queries are operated on by the "or" operator (any boolean operator for that matter), they are executed and evaluated in a short circuit manner. Queries evaluate to true if they have results, false if not. So, if the regular query has results, the alternate query will not execute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM