Reputation: 2614
I have an application with a few models listed below:
devices.Device
buildings.Building
buildings.Stack
buildings.Switch
rooms.Room
In my program, I accept a CSV
file with data. Then I parse it into JSON
representing each model and use get_or_create()
to add the data into the database. Here is an example:
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"
And the above is working well. However, I tried the code below, and could not get it to work:
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"
Which causes this error:
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
I suspect that it has to do with the way the models are constructed (which wasn't done by me). Could anyone suggest how to modify the above code so I could insert Switches and Stacks using get_or_create()
?
And, here is stack and switch from /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))
Upvotes: 0
Views: 202
Reputation: 2614
I needed to import Switch and Stack. I changed:
from buildings.models import Building
to from buildings.models import Building, Switch, Stack
Upvotes: 1