Query.get raising Object matching query does not exist Error - django

Please I need help with this code:
>>> t = Transaction.objects.filter(paid=True)
>>> t
[<Transaction: ac0e95f6cd994cc39807d986f7a10d4d>, <Transaction: 7067361871fd459f
aa144988ffa22c7c>, <Transaction: 134e5ab4b0a74b5a985ff53e31370818>, <Transaction
: ef451670efad4995bff755621c162807>]
>>> t[0]
<Transaction: ac0e95f6cd994cc39807d986f7a10d4d>
>>> t[0].branch_name
<Branch: WAREHOUSE ROAD>
>>> Transaction.objects.get(branch_name='WAREHOUSE ROAD')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\mana
ger.py", line 132, in get
return self.get_query_set().get(*args, **kwargs)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 344, in get
num = len(clone)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 82, in __len__
self._result_cache = list(self.iterator())
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 273, in iterator
for row in compiler.results_iter():
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\sql\
compiler.py", line 680, in results_iter
for rows in self.execute_sql(MULTI):
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\sql\
compiler.py", line 735, in execute_sql
cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\backends\ut
il.py", line 34, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\backends\my
sql\base.py", line 86, in execute
return self.cursor.execute(query, args)
File "build\bdist.win32\egg\MySQLdb\cursors.py", line 176, in execute
if not self._defer_warnings: self._warning_check()
File "build\bdist.win32\egg\MySQLdb\cursors.py", line 92, in _warning_check
warn(w[-1], self.Warning, 3)
Warning: Truncated incorrect DOUBLE value: 'WAREHOUSE ROAD'
Here is Branch and Transaction models:
class Branch(models.Model):
""" Branch """
bid = models.AutoField(primary_key=True)
institution = models.CharField(max_length=50)
branchcode = models.CharField(max_length=50)
name_branch = models.CharField(max_length=255)
name_branch_short = models.CharField(max_length=50)
address_1 = models.CharField(max_length=100)
name_city = models.CharField(max_length=50)
name_state = models.CharField(max_length=50)
sector = models.CharField(max_length=50)
class Meta:
db_table = u'branch'
def __unicode__(self):
return self.name_branch
class Transaction(models.Model):
"""Gateway transactions"""
id = models.AutoField(primary_key=True)
tpin = UUIDField(max_length=32, blank=True, editable=False,\
help_text='Transaction Payment Identification Number')
user_id = models.IntegerField(help_text='The user who made the transaction')
amount = models.DecimalField(max_digits=14, decimal_places=2, \
help_text='Transaction amount')
identifier = models.CharField(max_length=100, blank=True, \
help_text='A unique identifier provided by the student')
institution = models.ForeignKey(Institution, related_name='transactions')
financial_institution = models.ForeignKey('FinancialInstitution', blank=True, null=True, related_name='transactions', help_text='The financial institution this transaction was updated in')
branch_name = models.ForeignKey(Branch, blank=True, null=True, related_name='transactions', \
help_text='The bank branch where this transaction is originating from')
paid = models.BooleanField(default=False)
teller_no = models.CharField(max_length=20, blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
audit_log = AuditLog(exclude=['created', 'updated', ])
def __unicode__(self):
return self.tpin
def natural_key(self):
""" A natural key is a tuple of values that can be used to uniquely identify an object
instance without using the primary key value.
"""
return self.tpin
I tried to serialize Transaction like this:
>>> from django.core import serializers
>>> serializers.serialize('csv', t)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\core\serialize
rs\__init__.py", line 91, in serialize
s.serialize(queryset, **options)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\core\serialize
rs\base.py", line 48, in serialize
self.handle_fk_field(obj, field)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\core\serialize
rs\python.py", line 48, in handle_fk_field
related = getattr(obj, field.name)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\fiel
ds\related.py", line 315, in __get__
rel_obj = QuerySet(self.field.rel.to).using(db).get(**params)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 349, in get
% self.model._meta.object_name)
DoesNotExist: Branch matching query does not exist.
I don't understanding why get is returning DoesNotExists on Branch. I showed an example above which shows that Branch has a record in Transaction.
Looping through t I get a result, but then followed by DoesNotExist: Branch matching query does not exist
>>> for i in t:
... i.branch_name
...
<Branch: WAREHOUSE ROAD>
Traceback (most recent call last):
File "<console>", line 2, in <module>
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\fiel
ds\related.py", line 315, in __get__
rel_obj = QuerySet(self.field.rel.to).using(db).get(**params)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 349, in get
% self.model._meta.object_name)
DoesNotExist: Branch matching query does not exist.
Please help. Thanks

This query:
Transaction.objects.get(branch_name='WAREHOUSE ROAD')
filters for branch_name which is a ForeignKey field. To query on that name, you should use two underscores:
Transaction.objects.get(branch_name__name_branch='WAREHOUSE ROAD')
Not the most convenient names for your fields...

Related

Django Faker Recursive Foreign Key

I am trying to create a seeding script using Faker. In my models.ContentCategory, the parent_category has a recursive foreign key. However, I could not find a way to translate this into my faker script. I am really open to all kinds of helps!
here is my models.py:
class ContentCategory(models.Model):
name = models.CharField(blank=False, null=False, max_length=100)
description = models.CharField(blank=False, null=False, max_length=100)
parent_category = models.ForeignKey(
"self", on_delete=models.DO_NOTHING, null=True, blank=True, parent_link=True,
)
# down here should be fixed after creating the sections model
parent_section = models.ForeignKey(
Sections, on_delete=models.CASCADE, blank=True, null=True
)
def __str__(self):
return self.name
class Meta:
verbose_name = "content category"
verbose_name_plural = "Content Categories"
and here is the handler snippet:
#seeding Content Category
for _ in range(4):
name = fake.word(ext_word_list=None)
description = fake.sentence(nb_words=15, variable_nb_words=True, ext_word_list=None)
#creating ids and parent ids
cid = random.randint(1,4)
# creating key for Sections
ptid = random.randint(1,14)
ContentCategory.objects.create(
name=name, description=description, parent_category=cid, parent_section=ptid
)
check_content_categories = ContentCategory.objects.count().all()
here is the full error log:
python manage.py seed
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/home/myyagis/meethaq/be/be/api/management/commands/seed.py", line 104, in handle
ContentCategory.objects.create(
File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/query.py", line 420, in create
obj = self.model(**kwargs)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/base.py", line 483, in __init__
_setattr(self, field.name, rel_obj)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 206, in __set__
raise ValueError(
ValueError: Cannot assign "1": "ContentCategory.parent_category" must be a "ContentCategory" instance.
Thank you in advance!
Solved:
In the model, the foreign key tables were already accepting blank=True, null=True, hence, I discarded these from the seeder script, it automatically filled the db with the null values.
Better solutions for non-nullable fields :
Model.objects.order_by('?').first() confirmed using.
recursive foreign key accepts the model's own name as the Model name.
example for the model UserCategory:
for _ in range(200):
category = UserCategory.objects.order_by('?').first()
email = fake.unique.ascii_free_email()
password = fake.unique.word(ext_word_list=None)
gender =fake.api_gender()
first_name = fake.unique.first_name()
last_name = fake.unique.last_name()
phone_number = fake.country_calling_code() + fake.phone_number()
birthday = fake.unique.date_of_birth()

Value Error when assign to foreign key field while creating the object

I have the following Models
from django.db import models
class League(models.Model):
league_id = models.IntegerField()
country = models.ForeignKey('Country', on_delete = models.CASCADE)
name = models.CharField(max_length = 50)
logo = models.CharField(max_length = 250)
season = models.IntegerField()
season_start = models.DateField()
season_end = models.DateField()
standings = models.BooleanField(default= False)
class Country(models.Model):
country = models.CharField(max_length = 20, primary_key=True)
country_id = models.IntegerField()
I created custom management command to get data from API then extract disered data from API responce and create object of model based on this data. My custom management command code
from django.core.management.base import BaseCommand, CommandError
from data.models import League, Country
import requests
import json
def extracting_league():
response = requests.get("https://api-football-v1.p.rapidapi.com/leagues", headers={"X-RapidAPI-Key": "rRVyARf9ESmshWSiNIkYcTr0jp1nQh2JjsnNGNlcEYXM1XI"})
league = json.loads(response.text)
return league
parsed_league = extracting_league()
print(parsed_league)
def pars():
leagues = parsed_league['api']['leagues']
for id in parsed_league['api']['leagues']:
lg_id = leagues[id]["league_id"]
lg_name = leagues[id]["name"]
lg_country = Country.objects.get_or_create(country = leagues[id]["country"])
lg_logo = leagues[id]["logo"]
lg_season = leagues[id]["season"]
One_league = League.objects.create(league_id = lg_id, country = lg_country, name = lg_name, logo = lg_logo, season = leagues[id]["season"], season_start = leagues[id]["season_start"], season_end = leagues[id]["season_end"], standings = leagues[id]["standings"])
One_league.save()
print(One_league)
class Command(BaseCommand):
def handle(self, **options):
extracting_league()
pars()
When i run script with python manage.py 'custom management commmand' i see in console the following error notifications
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
__init__.py", line 381, in execute_from_command_line
utility.execute()
File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
base.py", line 353, in execute
output = self.handle(*args, **options)
File "D:\Python\my_projects\forecast\project\forecasting\data\management\comma
nds\extract_league.py", line 70, in handle
pars()
File "D:\Python\my_projects\forecast\project\forecasting\data\management\comma
nds\extract_league.py", line 25, in pars
One_league = League.objects.create(league_id = lg_id, country = lg_country,
name = lg_name, logo = lg_logo, season = leagues[id]["season"], season_start = l
eagues[id]["season_start"], season_end = leagues[id]["season_end"], standings =
leagues[id]["standings"])
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\manage
r.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\query.
py", line 411, in create
obj = self.model(**kwargs)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\base.p
y", line 467, in __init__
_setattr(self, field.name, rel_obj)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\fields
\related_descriptors.py", line 210, in __set__
self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "(<Country: Country object (Turkey)>, False)": "League
.country" must be a "Country" instance.
I can not to understand the following traceback message
ValueError: Cannot assign "(<Country: Country object (Turkey)>, False)": "League
.country" must be a "Country" instance.
It seems like in my Country model table is not country by Turkey name but when i look at table in PGadmin i have Turkey country in the Country table. Any suggestions
The django method get_or_create returns a tuple of (object, created), so you can use next solution:
lg_country, _ = Country.objects.get_or_create(country = leagues[id]["country"])

How can I resolve this error? TypeError: 'NoneType' object is not callable

I am trying to programmatically creating a bunch of db objects and auto-save them to the db using the code below. But for some reason, I get the error below when I try to save the object (i.e. Tender object). The line the triggers the error is tender_obj.save() in the save_tender_to_db() function. What could be causing this problem?
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 353, in execute
output = self.handle(*args, **options)
File "C:\PROJECTS\leadshub\tender_matching_engine\management\commands\scrap_etenders.py", line 8, in handle
main()
File "C:\PROJECTS\leadshub\Tender_Loader\etenders_scraper.py", line 52, in main
save_tender_to_db(entry)
File "C:\PROJECTS\leadshub\Tender_Loader\etenders_scraper.py", line 129, in save_tender_to_db
description=container_tag[0]
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py", line 413, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 718, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 748, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 831, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 869, in _do_insert
using=using, raw=raw)
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py", line 1136, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 1288, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 1241, in as_sql
for obj in self.query.objs
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 1241, in <listcomp>
for obj in self.query.objs
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 1240, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "C:\Users\ACER\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 1168, in prepare_value
value = value.resolve_expression(self.query, allow_joins=False, for_save=True)
TypeError: 'NoneType' object is not callable
Please have a look at my code below.
#This is the model that stores the tender.
class Tender(models.Model):
tenderCategory = models.ManyToManyField(Category, blank=False) #this field holds the tender category, e.g. construction, engineering, human resources etc.
tenderProvince = models.ManyToManyField(Province, blank=False) #this is the province the tender was advertised from.
buyersName = models.CharField(max_length=100) #this is the name of the Buyer e.g. Dept. of Transport, Transnet, Dept of Agriculture etc.
summary = models.TextField(blank=False) #this is the tender title as per the Buyer.
refNum = models.CharField(max_length=100) #tender ref number as per the Buyer.
issueDate = models.DateTimeField(blank=True, null=True) #date the tender was published
closingDate = models.DateTimeField(default=timezone.now, blank=True, null=True) #tender closing date
siteInspectionDate = models.DateTimeField(blank=True, null=True)
siteInspection = RichTextField(blank=True, null=True) #site inspection date, if any
enquiries = RichTextField(blank=True, null=True) #this field stores details of the contact person, for the tender.
description = RichTextField(blank=True, null=True) #this is the body of the tender. the tender details are captured here.
assigned_keywords = models.ManyToManyField(Keywords, blank=True)
matched = models.BooleanField(default=False, blank=False)
capture_date = models.DateField(default=timezone.now, blank=False, null=False)
date_assigned = models.DateField(blank=True, null=True)
tDocLinks = RichTextField(blank=True)
def check_if_expired(self):
if self.closingDate < timezone.now():
return True
else:
return False
class Meta:
ordering = ['-closingDate']
def save_tender_to_db(data_rec_str):
try:
url_data_ls = data_rec_str.split(';')
sauce_2 = urllib.request.urlopen('http://www.etenders.gov.za{}'.format(url_data_ls[0]))
soup_2 = BeautifulSoup(sauce_2, 'html.parser')
# finds the container div in the html.
container_tag = soup_2.findAll('div', {'class': 'fieldset-wrapper'})
if len(container_tag) == 1:
tender_obj = Tender(
# tenderCategory=Category.objects.get(pk=1),
# tenderProvince=Province.objects.get(pk=1),
summary=url_data_ls[5].strip(),
refNum=url_data_ls[1].strip(),
issueDate=extract_date(url_data_ls[3].strip(), 2),
description=container_tag[0],
matched=False,
capture_date=timezone.now
)
tender_obj.save() #this is the line that triggers the error
else:
tender_obj = Tender(
# tenderCategory=Category.objects.get(pk=1),
# tenderProvince=Province.objects.get(pk=1),
summary=url_data_ls[5].strip(),
refNum=url_data_ls[1].strip(),
issueDate=extract_date(url_data_ls[2].strip(), 1),
closingDate=extract_date(url_data_ls[3], 2),
siteInspectionDate=extract_date(url_data_ls[4], 2),
description=container_tag[0],
tDocLinks = container_tag[1],
matched=False,
capture_date=timezone.now
)
tender_obj.save() #this is the line that triggers the error
except urllib.error.URLError as e:
print(e)
Lastly, when I uncomment the two lines below, I get the subsequent error. How can I solve this?
# tenderCategory=Category.objects.get(pk=1),
# tenderProvince=Province.objects.get(pk=1),
TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use tenderCategory.set() instead.

Django reversed OneToOne relation with select_related

I have below model and I want to perform below query:
Post.objects.select_related(
'previous_post', 'next_post'
).get(id=some_id)
# models.py
class Post(models.Model):
title = models.CharField(max_length=60, unique=True)
description = models.TextField()
content = models.TextField()
previous_post = models.OneToOneField('self', null=True, blank=True,
related_name='next_post',
on_delete=models.PROTECT)
For some reason it does not work with next_post parameter, as I get following error:
raise IndexError("Number of args exceeds number of fields")
IndexError: Number of args exceeds number of fields
Theoretically I can live without select_related, but I would prefer not to give up it in this case and I am really curious whether I am doing something wrong or this is just a Django bug.
Full traceback:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/query.py", line 381, in get
num = len(clone)
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/query.py", line 240, in __len__
self._fetch_all()
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/query.py", line 1074, in _fetch_all
self._result_cache = list(self.iterator())
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/query.py", line 72, in __iter__
rel_populator.populate(row, obj)
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/query.py", line 1715, in populate
obj = self.model_cls.from_db(self.db, self.init_list, obj_data)
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/base.py", line 460, in from_db
new = cls(*values)
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/base.py", line 372, in __init__
raise IndexError("Number of args exceeds number of fields")
IndexError: Number of args exceeds number of fields
It looks like a bug in Django. I can reproduce in 1.8 and 1.9, but not in the master branch.
Doing a git bisect, tt appears to have been fixed by ticket 26207, so it should be fixed in Django 1.10.

How does django/sqllite3 build database for testing?

Hi I'm attempting to write some unittests for my django web application but I'm running into some database problems when trying to run my tests. I'm using Factory Boy in some places in order to create instances for the tests (https://github.com/dnerdy/factory_boy is the repo) but I'm running into some problems when I attempt to run my tests. I'm getting database errors such as: no such column when I try to run my tests and table already exits errors when I try to run ./manage.py syncdb (I'll include the actual errors below). I'm using the default sqlite3 database settings for testing so the test DB is created to run the tests then destroyed afterward automatically.
Here are the pertinent sections of my settings.py file
if 'test' in sys.argv or 'jenkins' in sys.argv:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test_ndptc'
}
}
Here is the model that is throwing the error.
class CourseManager(models.Manager):
def get_query_set(self):
return super(CourseManager, self).get_query_set().order_by('CourseName')
class Course(models.Model):
"""
"""
CourseName = models.CharField(max_length=80)
ShortName = models.CharField(max_length=50)
CourseNumber = models.CharField(max_length=50)
TrainingProvider = models.ForeignKey(TrainingProvider)
TrainingType = models.ForeignKey(TrainingType)
CourseType = models.ForeignKey(CourseType)
ModuleCount = models.IntegerField()
ContactHours = models.CharField(max_length=5)
Certified = models.BooleanField()
Description = models.TextField(null=True, blank=True)
TargetAudience = models.TextField(null=True, blank=True)
Prerequisites = models.TextField(null=True, blank=True)
Requirements = models.TextField(null=True, blank=True)
Icon2d = models.FileField(upload_to='icons/', null=True, blank=True)
Icon3d = models.FileField(upload_to='icons/', null=True, blank=True)
Status = models.IntegerField(null=True)
UpdateUser = models.ForeignKey(User, null=True)
UpdateDate = models.DateField(null=True)
Featured = models.BooleanField(verbose_name='is featured?')
objects = CourseManager()
Here is the factory where the error occurs.
class TestFactory(factory.Factory):
FACTORY_FOR = Test
Course = random.choice(Course.objects.all())
EffectiveDate = '01/01/2012'
Type = random.choice(TestType.objects.all())
Label = 'test_label'
Status = 1
UpdateUser = factory.LazyAttribute(lambda a: UserFactory())
UpdateDate = '01/01/2012'
And finally here is the error that occurs when I run ./manage.py test
Traceback (most recent call last):
File "./manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1- py2.7.egg/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/core/management/commands/test.py", line 37, in handle
failures = test_runner.run_tests(test_labels)
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/test/simple.py", line 358, in run_tests
suite = self.build_suite(test_labels, extra_tests)
File "/home/brandon/course-management/Testing/runner.py", line 17, in build_suite
suite = unittest.defaultTestLoader.loadTestsFromNames(test_labels)
File "/usr/lib/python2.7/unittest/loader.py", line 128, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names]
File "/usr/lib/python2.7/unittest/loader.py", line 91, in loadTestsFromName
module = __import__('.'.join(parts_copy))
File "/home/brandon/course-management/Testing/admin_tests.py", line 5, in <module>
from Testing.Factories.course_factory import *
File "/home/brandon/course-management/Testing/Factories/course_factory.py", line 19, in <module>
class TestFactory(factory.Factory):
File "/home/brandon/course-management/Testing/Factories/course_factory.py", line 22, in TestFactory
Course = random.choice(Course.objects.all())
File "/usr/lib/python2.7/random.py", line 274, in choice
return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/query.py", line 82, in __len__
self._result_cache = list(self.iterator())
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/query.py", line 273, in iterator
for row in compiler.results_iter():
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/sql/compiler.py", line 680, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/models/sql/compiler.py", line 735, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/django/db/backends/sqlite3/base.py", line 234, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.DatabaseError: no such column: Course_course.ShortName
I think that random.choice is running on a empty list. I think you could use a lazy attribute, e.g.
#factory.lazy_attribute
def course(a):
""" Creates a course if none exist
"""
if Course.objects.count() == 0:
course = CourseFactory()
return course
else:
return random.choice(Course.objects.all())