I already have a database named "mydb", where I have a table called "AERODROME".
My models.py looks like this:
from django.db import models
class Aerodrome(models.Model):
Name = models.CharField(max_length=48)
Latitude = models.DecimalField(decimal_places=4, max_digits=7)
Longitude = models.DecimalField(decimal_places=4, max_digits=7)
And I have this method at views.py:
from django.shortcuts import render
from helloworld.models import Aerodrome
def aerodromes(request):
return render(request, 'aerodromes.html', {'aerodromes': Aerodrome.objects.all()})
At my templates folder, I have aerodromes.html, which is quite simple too:
<!doctype html>
<html>
<head>
</head>
<body>
<table>
{% for aerodrome in aerodromes %}
<tr>
<td>{{ aerodrome.Name }}</td>
<td>{{ aerodrome.Longitude }}</td>
<td>{{ aerodrome.Latitude }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
When I test through my browser, I get an error, because it looks like it's accessing the table with a wrong name. My application is called "helloworld" since it's a test, and instead of accessing to mydb.AERODROMES, it is accessing to mydb.helloworld_aerodrome (Also note the case sensitive problem).
Since I already had the database populated, I haven't run syncdb (I understood it wasn't neccessary, but maybe this is the problem).
So, the problem is that I don't know why it is adding "helloworld_" to the table name, and also that I still don't know for sure where exactly am I fixing the table name (and from there comes the case sensitive problem having "aerodrome" and not "AERODROMES").
Any help here?
Use the Meta
class (documentation here) inside your models.py
model definition:
class Aerodrome(models.Model):
Name = models.CharField(max_length=48)
Latitude = models.DecimalField(decimal_places=4, max_digits=7)
Longitude = models.DecimalField(decimal_places=4, max_digits=7)
class Meta:
db_table = 'AERODROMES'
This will override the default naming scheme for model tables in the SQL database.
You can also add the managed
attribute to control whether or not python manage.py syncdb
and python manage.py flush
manage the table.
class Aerodrome(models.Model):
# ...
class Meta:
db_table = 'AERODROMES'
managed = False
With this you can syncdb
without fear of wiping your data.
from the django docs: It is strongly advised that you use lowercase table names when you override the table name via db_table, particularly if you are using the MySQL backend. See the MySQL notes for more details.
https://docs.djangoproject.com/en/1.11/ref/databases/#table-names
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With