简体   繁体   English

更多Pythonic / Django风格的方式来编写此代码?

[英]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. 但是,您应该添加一个明确的异常来捕获,因为except语句except的空白可能非常危险。 Imagine a situation where using internal_id=line[5] raises Author.MultipleItemsReturned . 想象一下使用internal_id=line[5]引发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 :) 好的,在这种情况下,可能不是这样,但是总的来说, except s except ,空白是不好的:)

IMO, this reads better: IMO,这读起来更好:

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). 一些注意事项:您应该能够保证这些内部ID是唯一的(可以肯定地说,因为您使用的是get方法)。 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. 如果有结果,则查询为true;否则为false。 So, if the regular query has results, the alternate query will not execute. 因此,如果常规查询有结果,则备用查询将不会执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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