如何优化向数据存储添加数据的代码?
我有以下代码(对于 Country
和 City
类 key_name
是数字 ID,在开头添加“i”):
def add_country(country, country_name):
if country and country_name and country_name != '':
return Country.get_or_insert('i'+str(country), country_name=country_name)
else:
return None
def add_city(city, city_name, country):
if country and city and city_name and city_name != '':
return City.get_or_insert('i'+str(city), city_name=city_name, parent=country)
else:
return None
是否正确代码或者可以以某种方式优化吗?
I have the following code (for Country
and City
classes key_name
is numeric id with addition of 'i' at the beginning):
def add_country(country, country_name):
if country and country_name and country_name != '':
return Country.get_or_insert('i'+str(country), country_name=country_name)
else:
return None
def add_city(city, city_name, country):
if country and city and city_name and city_name != '':
return City.get_or_insert('i'+str(city), city_name=city_name, parent=country)
else:
return None
Is it correct code or can it be optimized somehow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无需在 ID 前添加字符前缀 - 只需将它们转换为字符串并按原样使用即可。否则,这可能没问题,尽管在不了解如何使用它以及如何获取对象的情况下很难知道。
You don't need to prefix your IDs with a character - simply convert them to a string and use them as-is. Otherwise, this is probably fine, though it's hard to know without seeing how you're using it and how you fetch the objects.