Reputation: 632
I have created a simple Django
application which tries to access table named fruits
present in PostgreSQL
database and display its contents. I followed the official Django
documentation and implemented below code as far as I understand. But below procedure is incomplete I believe as fruits.objects.all()
is failing to fetch any data. I am missing something can anybody point it out any help would be appreciated.
Table: fruits
models.py
from django.db import models
class fruits(models.Model):
ID = models.CharField(max_length=20)
Name = models.CharField(max_length=20)
def __str__(self):
return self.Name
views.py
from database.models import fruits
def index(request):
data = fruits.objects.all()
print(len(data))
for item in data:
print(item)
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '<database_name>',
'USER': '<user_name>',
'PASSWORD': '<password>',
'HOST': '<host_name>',
'PORT': '',
}
}
Upvotes: 3
Views: 4311
Reputation: 47354
By default Django will create new table appname_modelname
for model. So in your case this queryset fruits.objects.all()
fetch data from app_fruits
table, not fruits
. You can specify table name using db_table
meta option. For example to link model fruits
with existing table fruits
add following Meta
to the model:
class fruits(models.Model):
ID = models.IntegerField(max_length=20)
Name = models.CharField(max_length=20)
class Meta:
db_table = 'fruits'
def __str__(self):
return self.Name
UPD
Django expect id
field to be primary key by default not ID
, to change this add primary_key
option to ID
field:
ID = models.IntegerField(max_length=20, primary_key=True)
Upvotes: 1