[英]Database table names with Django
我已經有一個名為“mydb”的數據庫,我有一個名為“AERODROME”的表。
我的models.py看起來像這樣:
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)
我在views.py上有這個方法:
from django.shortcuts import render
from helloworld.models import Aerodrome
def aerodromes(request):
return render(request, 'aerodromes.html', {'aerodromes': Aerodrome.objects.all()})
在我的模板文件夾中,我有aerodromes.html,這也很簡單:
<!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>
當我通過我的瀏覽器測試時,我收到一個錯誤,因為它看起來像是用錯誤的名稱訪問該表。 我的應用程序被稱為“helloworld”,因為它是一個測試,而不是訪問mydb.AERODROMES,它訪問mydb.helloworld_aerodrome(還要注意區分大小寫的問題)。
由於我已經填充了數據庫,我沒有運行syncdb(我知道這不是必要的,但也許這就是問題)。
所以,問題是我不知道為什么它會在表名中添加“helloworld_”,而且我還不確定我在哪里修正表名(並且從那里開始出現區分大小寫)有“機場”而不是“AERODROMES”的問題。
這里有什么幫助?
在models.py
模型定義中使用Meta
類( 文檔 ):
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'
這將覆蓋SQL數據庫中模型表的默認命名方案。
您還可以添加managed
屬性來控制是否python manage.py syncdb
和python manage.py flush
管理表。
class Aerodrome(models.Model):
# ...
class Meta:
db_table = 'AERODROMES'
managed = False
有了這個,你可以syncdb
而不用擔心擦除你的數據。
明確指定模型的表名應該有所幫助:
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)
class Meta:
db_table = 'AERODROMES'
來自django文檔: 強烈建議您在通過db_table覆蓋表名時使用小寫表名,尤其是在使用MySQL后端時。 有關更多詳細信息,請參閱MySQL說明。
https://docs.djangoproject.com/en/1.11/ref/databases/#table-names
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"
如果您在外部預填充表格。 注意每個記錄/字段中的數據是否合適/兼容。
但是,您必須創建syncdb
因為創建了django所需的其他表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.