Hi All,
Just started playing around with Django. Created a basic app. And am trying to create a model and save data to corresponding table in sqlite. Wrote a test to check the model and save operation. But somehow the data is not getting saved in the table. The table has got created when i ran migrate command. The model is pretty simple:
from django.db import models
class JD(models.Model):
job_id = models.TextField()
role = models.CharField(max_length=100)
experience = models.IntegerField()
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
Test is as follows:
from django.test import TestCase
from .jd import JD
class JDModelTest(TestCase):
def test_job_id_label(self):
JD.objects.create(job_id='1', role='Software Engineer', experience=2)
jd = JD.objects.get(id=1)
field_label = jd._meta.get_field('job_id').verbose_name
self.assertEquals(field_label, 'job id')
When I run the tests, they do pass and i dont see any error/exception:
:test_job_id_label
./myapp/allmodels/test_jd.py::JDModelTest::test_job_id_label Passed
Total number of tests expected to run: 1
Total number of tests run: 1
Total number of tests passed: 1
Total number of tests failed: 0
Total number of tests failed with errors: 0
Total number of tests skipped: 0
Finished running tests!
The table is created but it doesnt have any record.
I debugged and the problem seems to be due to the code “if isinstance(params, Mapping)” in the ./lib/python3.10/site-packages/django/db/backends/sqlite3/base.py
def execute(self, query, params=None):
if params is None:
return super().execute(query)
# Extract names if params is a mapping, i.e. "pyformat" style is used.
param_names = list(params) if isinstance(params, Mapping) else None
query = self.convert_query(query, param_names=param_names)
return super().execute(query, params)
The “params” parameter is a tuple rather than a dictionary or a list. Its created in the function " def as_sql(self)" of /lib/python3.10/site-packages/django/db/models/sql/compiler.py (the “tuple” in the list)
if r_sql:
result.append(r_sql)
params += [self.returning_params]
return [(" ".join(result), tuple(chain.from_iterable(params)))]
Following is my project structure:
TRYDJANGO (WORKSPACE)
├── TryDjango
│ ├── .vscode
│ │ └── settings.json
│ └── tryapp
│ ├── myapp
│ │ ├── __pycache__
│ │ │ └── allmodels
│ │ └── __pycache__
│ │ └── __init__.py
│ │ └── jd.py
│ │ → test_jd.py
│ │ └── migrations
│ │ ├── __init__.py
│ │ ├── admin.py
│ │ ├── apps.py
│ │ ├── models.py
│ │ └── tests.py
│ │ └── views.py
│ └── tryapp
│ ├── __pycache__
│ └── __init__.py
│ └── asgi.py
│ └── settings.py
│ → urls.py
│ └── wsgi.py
└── db.sqlite3
→ manage.py
I am using conad env with python 3.10 and Django 4.2.6, and have also tried with python 3.11.5 and Django 4.2.7.
It is likely that I am missing something very basic, but havent been able to put my finger on. Any help will be greatly appreciated.
TIA
~Anand.