[英]UnboundLocalError: local variable 'region' referenced before assignment
I am trying to create an object but stacked with this problem, but it seams for me that i didn't make any mistake.我正在尝试创建一个对象,但遇到了这个问题,但对我来说,我没有犯任何错误。
def handle(self, *args, **options):
for entry in get_dataset():
oblast = Place.objects.get_or_create(name=entry.get('OBL_NAME'))
if entry.get('REGION_NAME') is not None:
region = Place.objects.get_or_create(name=entry.get('REGION_NAME'),
parent=oblast)
if entry.get('CITY_NAME') is not None:
city = Place.objects.get_or_create(name=entry.get('CITY_NAME'),
parent=region)
I could not understand why region variable doesn't work我不明白为什么区域变量不起作用
In you last part you have在你的最后一部分你有
city = Place.objects.get_or_create(..., parent=region)
The variable region
does not seem to be defined if the first if
is false (the code execution never gets to assign a value to region
in that case).如果第一个
if
为 false,则似乎没有定义变量region
(在这种情况下,代码执行永远不会为region
分配值)。
Maybe you need to initialize the variable outside of the first if
(maybe like region = None
or something just before the first if
).也许你需要在第一个
if
之外初始化变量(可能像region = None
或者在第一个if
之前的东西)。 Here is a example of how you could do it, but the exact way depends on the rest of your code:这是一个如何做到这一点的示例,但确切的方法取决于您的代码的其余部分:
oblast = Place.objects.get_or_create(name=entry.get('OBL_NAME'))
region = None
if entry.get('REGION_NAME') is not None:
region = ...
if entry.get('CITY_NAME') is not None:
city = Place.objects.get_or_create(
name=entry.get('CITY_NAME'),
parent=region)
Somehow your code doesn't meet your first if condition and therefore your region variable doesn't get created.不知何故,您的代码不符合您的第一个 if 条件,因此您的区域变量不会被创建。 You could do something like this:
你可以这样做:
def handle(self, *args, **options):
for entry in get_dataset():
oblast = Place.objects.get_or_create(name=entry.get('OBL_NAME'))
if entry.get('REGION_NAME') is not None:
region = Place.objects.get_or_create(name=entry.get('REGION_NAME'),
parent=oblast)
if entry.get('CITY_NAME') is not None and region:
city = Place.objects.get_or_create(name=entry.get('CITY_NAME'),
parent=region)
else:
city = Place.objecys.get_or_create(name=entry.get('CITY_NAME'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.