gpt4 book ai didi

python - Django 的数据库表名

转载 作者:可可西里 更新时间:2023-11-01 06:53:59 24 4
gpt4 key购买 nike

我已经有一个名为“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 类 ( documentation here ):

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 syncdbpython manage.py flush是否管理表.

class Aerodrome(models.Model):
# ...

class Meta:
db_table = 'AERODROMES'
managed = False

有了它,您可以syncdb,而不必担心删除您的数据。

关于python - Django 的数据库表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16421574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com