Django到Heroku,如何将sqlite3数据迁移到postgres



我试图在heroku上托管一个网站,但我一直收到这个错误

文件"app/.horoku/python/lib/python3.9/site packages/django/db/backends/utils.py";,第84行,在_execute中return self.cursor.execute(sql,params(django.db.utils.ProgrammingError:relationship"家庭_产品";不存在第1行:。。。家庭产品"价格"家庭产品"鼻涕虫";来自"主页(_P(。。。

每当我尝试使用时

heroku run python
manage.py migrate -a appname

我主要用这个视频作为主持的参考。

还有这个StackOverflow问题,这篇文章并没有对这个问题进行太多的阐述。

这是我的settings.py

"""
Django settings for Corbett_Jewelry project.
Generated by 'django-admin startproject' using Django 3.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path
import os
import django_heroku
import dj_database_url
from decouple import config
import psycopg2
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False'

ALLOWED_HOSTS = ['127.0.0.1']

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home'
]
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'Corbett_Jewelry.urls'
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
WSGI_APPLICATION = 'Corbett_Jewelry.wsgi.application'
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True)
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
django_heroku.settings(locals())

我的models.py:

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    image = models.ImageField(blank=True)
    desc = models.TextField()
    price = models.IntegerField()
    slug = models.SlugField(unique=True, default=None)
    def __str__(self):
        return self.name
class Images(models.Model):
    product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE)
    img = models.ImageField(upload_to='images/')
    def __str__(self):
        return self.product.name
    
class Beads(models.Model):
    name = models.CharField(max_length=200)
    price = models.IntegerField()
    img = models.ImageField(upload_to='beads/')

我的Procfile:

web: gunicorn Corbett_Jewelry.wsgi

我的requirements.txt:

asgiref==3.4.1
cycler==0.10.0
dj-database-url==0.5.0
Django==3.2.9
django-heroku==0.3.1
gunicorn==20.1.0
kiwisolver==1.3.2
matplotlib==3.4.3
numpy==1.21.2
Pillow==8.3.2
psycopg2==2.9.2
pyparsing==2.4.7
python-dateutil==2.8.2
python-decouple==3.5
pytz==2021.3
selenium==3.141.0
six==1.16.0
sqlparse==0.4.2
urllib3==1.26.7
whitenoise==5.3.0

我不知道你还需要什么信息来解决这个问题。我很乐意提供任何信息,因为我已经为此绞尽脑汁一周了。

@Gamingapple。。。正如你在评论中所问的那样,我将努力为你的问题提供我能想到的所有可能的解决方案。

我从未使用过Heroku,但以下是我尝试的第一个解决方案

1.从Heroku的帮助文档中快速阅读显示,您可能没有按照Heroku认为的迁移最佳实践来运行迁移:https://help.heroku.com/GDQ74SU2/django-migrations这(或多或少(意味着你应该在本地运行迁移,向上推到Git,然后Heroku将在部署时自动运行迁移,它指出:

Then, add the following as the first line in your Procfile:
release: python manage.py migrate

但请注意,这也意味着您应该在本地开发中使用Postgres,而不是SQLite(正如您的标题所示(。

--除此之外,您似乎正在尝试通过应用程序运行迁移:manage.py migrate -a appname,Django确实有一些需要运行的常规迁移,所以我只尝试manage.py migrate

2.您在评论中注意到PyPi的dj_database_url包中的dj_database_url.config():https://pypi.org/project/dj-database-url/正在返回一个空字典。对我来说,在没有额外信息的情况下,我想说这就是当你手动尝试在Heroku实例中运行migrate时的问题所在;没有可查找或连接的数据库。要解决此问题,我会删除dj_database_url的使用(因为我也没有使用过它,我们正在调试(,并手动为Django的DATABASES编写连接字符串,如下所示:

pip install psycopg2或仅确保其符合要求/已安装。

将您的DATABASES属性设置更改为手动编写,以便您知道它是什么(我们正在调试,所以也许在您设置后,您可以使密码收集更加安全,比如作为环境变量(

DATABASES = {
   'default': {
       'ENGINE': 'django.db.backends.postgresql',
       'NAME': '[HEROKU DB NAME]',
       'USER': '[HEROKU DB USERNAME]',
       'PASSWORD': '[HEROKU PASSWORD]',
       'HOST': '{HEROKU HOST IP OR NAME FOR YOUR DB]',
       'PORT': '[HEROKU DB PORT]',
   }
}

正确之后,运行迁移命令:

python manage.py makemigrations

python manage.py migrate

最新更新