我的应用程序包含以下几种型号:
devices.Device
buildings.Building
buildings.Stack
buildings.Switch
rooms.Room
在我的程序中,我接受带有数据的CSV
文件。然后我将其解析为代表每个模型的JSON
并使用get_or_create()
将数据添加到数据库中。这是一个例子:
obj, created = Building.objects.get_or_create(
name=entry["fields"]["name"],
number=entry["fields"]["number"])
if created:
output += "Building was created!\n"
else:
output += "Building already exists!\n"
以上运作良好。但是,我尝试了下面的代码,但无法使其工作:
obj, created = Switch.objects.get_or_create(
stack=entry["fields"]["stack"],
number=entry["fields"]["number"],
ip=entry["fields"]["ip"],
num_ports=entry["fields"]["num_ports"])
if created:
output += "Switch was created!\n"
else:
output += "Switch already exists!\n"
导致此错误:
Traceback:
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
20. return view_func(request, *args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
20. return view_func(request, *args, **kwargs)
File "/opt/cutsheets/cutsheets/views.py" in import_data
156. output = process_xls_data(temp_dir)
File "/opt/cutsheets/cutsheets/views.py" in process_xls_data
113. obj, created = Switch.objects.get_or_create(
Exception Type: NameError at /import
Exception Value: global name 'Switch' is not defined
我怀疑它与模型的构建方式有关(我没有这样做)。任何人都可以建议如何修改上面的代码,以便我可以使用get_or_create()
?
而且,这是堆栈并从/buildings /models.py切换:
class Switch(models.Model):
stack = models.ForeignKey(Stack, null=True, related_name='switches')
number = models.PositiveIntegerField()
ip = models.IPAddressField()
num_ports = models.PositiveIntegerField()
def __unicode__(self):
return unicode(self.number)
@models.permalink
def get_absolute_url(self):
return ('buildings.views.switch', (self.stack.building.number, self.stack.number, self.number))
class Stack(models.Model):
building = models.ForeignKey(Building, related_name='stacks')
number = models.PositiveIntegerField()
num_switches = models.PositiveIntegerField()
def __unicode__(self):
return unicode(self.number)
@models.permalink
def get_absolute_url(self):
return ('buildings.views.stack', (self.building.number, self.number))
答案 0 :(得分:1)
我需要导入Switch和Stack。我改变了:
from buildings.models import Building
到from buildings.models import Building, Switch, Stack