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())
Related
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()
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"])
I am working with a Django application with Postgres Database.
My models are as follows:
from django.db import models
from django.contrib.auth.models import User as UserModel
from dynamicforms.mangers import TextQuestionManager, MCQManager, IntegerQuestionManager
from django.db.models.fields.related import OneToOneRel
from django.contrib.postgres import fields as postgres_fields
Qtypes = [(1, "Multiple Choice Question"), (2, "Text Question"), (3, "integer Type Question")]
COMPS = [(True, 'Yes'), (False, 'No')]
SECTIONS = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
class QuestionModel(models.Model):
qtype = models.IntegerField(null=False, choices=Qtypes)
text = models.TextField(max_length=500, null=False, blank=False)
description = models.TextField(max_length=1000, null=True, blank=True)
help_text = models.CharField(max_length=300, null=True, blank=True)
is_compulsory = models.BooleanField(default=True, null=False, choices=COMPS)
def __str__(self):
return self.text
class TextQuestionModel(QuestionModel):
nextQ = postgres_fields.ArrayField(models.IntegerField(blank=True, null=True), null=True, blank=True)
objects = TextQuestionManager()
class MCQModel(QuestionModel):
objects = MCQManager()
class Meta:
proxy = True
class IntegerQuestionModel(QuestionModel):
nextQ = postgres_fields.ArrayField(models.IntegerField(blank=True, null=True), null=True, blank=True)
objects = IntegerQuestionManager()
I made few changes to my schema.So i have to reset my DB.I reseted my DB and migrations and when im trying to run
python manage.py makemigrations
I am getting this error.I tried changing db and changing user and everything.I dont understand what made this error.
Unhandled exception in thread started by <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace instance at 0x7fa990057998>
Traceback (most recent call last):
File "/opt/pycharm/helpers/pydev/_pydev_bundle/pydev_monkey.py", line 553, in __call__
return self.original_func(*self.args, **self.kwargs)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run
autoreload.raise_last_exception()
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate
app_config.ready()
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/phani/Projects/Freewill/dynamicforms/admin.py", line 3, in <module>
from dynamicforms.forms import MCQFormAdmin, TextFormAdmin, IntegerFormAdmin
File "/home/phani/Projects/Freewill/dynamicforms/forms.py", line 6, in <module>
QS = [(i.id, i.text) for i in QuestionModel.objects.all()]
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 256, in __iter__
self._fetch_all()
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 1087, in _fetch_all
self._result_cache = list(self.iterator())
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 54, in __iter__
results = compiler.execute_sql()
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/phani/Projects/Freewill/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "dynamicforms_questionmodel" does not exist
LINE 1: ..."dynamicforms_questionmodel"."is_compulsory" FROM "dynamicfo...
^
Can someone help me with this?Thanks in advance
You reseted all files in project. But migrations history saved in django_migrations tables . You also must clean this table.
Are you deleted 'migrations' folder in your app?
I tried to insert a new field in my model and I got a DateTime Migration error, So I deleted those two fields and am trying to run "migrate" function which is not working , Make migration still work though.
D:\trydjango\src>python manage.py makemigrations
No changes detected
D:\trydjango\src>python manage.py migrate
Operations to perform:
Apply all migrations: contenttypes, auth, sessions, admin, posts
Running migrations:
Rendering model states... DONE
Applying posts.0009_auto_20170213_1754...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\python35\lib\site-packages\django\core\management\__init__.py", line
350, in execute_from_command_line
utility.execute()
File "C:\python35\lib\site-packages\django\core\management\__init__.py", line
342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\python35\lib\site-packages\django\core\management\base.py", line 348,
in run_from_argv
self.execute(*args, **cmd_options)
File "C:\python35\lib\site-packages\django\core\management\base.py", line 399,
in execute
output = self.handle(*args, **options)
File "C:\python35\lib\site-packages\django\core\management\commands\migrate.py
", line 200, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "C:\python35\lib\site-packages\django\db\migrations\executor.py", line 92
, in migrate
self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_ini
tial)
File "C:\python35\lib\site-packages\django\db\migrations\executor.py", line 12
1, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_
initial)
File "C:\python35\lib\site-packages\django\db\migrations\executor.py", line 19
8, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\python35\lib\site-packages\django\db\migrations\migration.py", line 1
23, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, projec
t_state)
File "C:\python35\lib\site-packages\django\db\migrations\operations\fields.py"
, line 62, in database_forwards
field,
File "C:\python35\lib\site-packages\django\db\backends\sqlite3\schema.py", lin
e 221, in add_field
self._remake_table(model, create_fields=[field])
File "C:\python35\lib\site-packages\django\db\backends\sqlite3\schema.py", lin
e 103, in _remake_table
self.effective_default(field)
File "C:\python35\lib\site-packages\django\db\backends\base\schema.py", line 2
10, in effective_default
default = field.get_db_prep_save(default, self.connection)
File "C:\python35\lib\site-packages\django\db\models\fields\__init__.py", line
728, in get_db_prep_save
prepared=False)
File "C:\python35\lib\site-packages\django\db\models\fields\__init__.py", line
1461, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\python35\lib\site-packages\django\db\models\fields\__init__.py", line
1440, in get_prep_value
value = super(DateTimeField, self).get_prep_value(value)
File "C:\python35\lib\site-packages\django\db\models\fields\__init__.py", line
1296, in get_prep_value
return self.to_python(value)
File "C:\python35\lib\site-packages\django\db\models\fields\__init__.py", line
1399, in to_python
parsed = parse_datetime(value)
File "C:\python35\lib\site-packages\django\utils\dateparse.py", line 93, in pa
rse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object
D:\trydjango\src>
Below is my Models.py file.
from django.db import models
from django.core.urlresolvers import reverse
class Invoice(models.Model):
active = models.BooleanField()
bu_field = models.CharField(max_length=10)
invoice_name = models.CharField(max_length=500)
sow_name = models.CharField(max_length=500)
probability = models.IntegerField()
sow_type = models.CharField(max_length=50)
sow_start_date = models.DateField()
sow_end_date = models.DateField()
project_id = models.CharField(max_length=500)
project_manager = models.CharField(max_length=500, null=True)
po_number = models.IntegerField()
sow_value = models.DecimalField(max_digits=8, decimal_places=2)
current_month = models.CharField(max_length=20)
current_year = models.CharField(max_length=5)
month_value = models.DecimalField(max_digits=8, decimal_places=2)
q1_value = models.IntegerField()
q2_value = models.IntegerField()
q3_value = models.IntegerField()
q4_value = models.IntegerField()
total_value_ofyear = models.IntegerField()
probability_month_value = models.IntegerField()
def __str__(self):
return self.invoice_name
def get_absolute_url(self):
return reverse("invoice:detail", kwargs={"id": self.id})
There are no new fields , everything is back as it was but not i am getting this error.
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...