通过django访问模型对象时,从表中删除的对象仍然存在

时间:2017-05-31 21:28:16

标签: python django postgresql django-models

我正在开发一个带有postgresql后端的django应用程序。我正在研究一个单独的python脚本来访问表(模型通过django)进行一些修改,然后启动修改记录的Web表单。在我的测试中,我已经进入了脚本之外的数据库并删除了记录,当我再次运行脚本时,删除的记录仍然存在。为什么会发生这种情况?如何在每次运行脚本时确保刷新表格?我已经尝试迭代我正在访问的模型中的对象并使用object.refresh_from_db(),但这似乎没有做任何事情。有人可以帮忙吗?

以下是我尝试访问现有记录的代码片段:

from django.conf import settings
    # from update import update_defaults
    # settings.configure(default_settings=update_defaults, DEBUG=True)
    os.environ['DJANGO_SETTINGS_MODULE'] = 'mapindex.settings'
    django.setup()
    # from django.conf import settings

from update.models import Mapindex
for m in Mapindex.objects.all():
         m.refresh_from_db()
         existing_oid_list.append(m.objectid)
         print m.sheetlabel, m.county, m.status
         if m.sheetlabel in img_list_shtlbls and m.status == 'Active':
             print 'setting', m.sheetlabel, 'status to superseded...'
             print 'superseded objectid =', m.objectid
             m.status = 'Superseded'
             m.publish = 'No'
             m.save()

哪些其他信息有助于发布?这是我的settings.py如果有帮助:

"""
Django settings for mapindex project.

Generated by 'django-admin startproject' using Django 1.11a1.

For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""

import os
import sys

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'urpz542i6mx*d07dbe&^ko1)u2w+z7n1er=6k913+)3ot89h2d'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'update.apps.UpdateConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_windows_tools',
]


MIDDLEWARE_CLASSES = [
    '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',
]

ROOT_URLCONF = 'mapindex.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 = 'mapindex.wsgi.application'


if 'test' in sys.argv:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'OPTIONS': {
                'options': '-c search_path=django,public'
            },
            'NAME': 'rowbasedata',
            'USER': 'postgres',
            'PASSWORD': 'pg*admin',
            'HOST': '10.32.2.193',
            'PORT': '5432'
        }
    }
else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'OPTIONS' : {
                   'options': '-c search_path=django,sde'
            },
            'NAME': 'rowbasedata',
            'USER': 'postgres',
            'PASSWORD': 'pg*admin',
            'HOST': '10.32.2.193',
            'PORT': '5432'
        }
    }


# Password validation
# https://docs.djangoproject.com/en/dev/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/dev/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/Los_Angeles'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'mapindex', 'static')
STATIC_URL = '/mapindex/static/'

1 个答案:

答案 0 :(得分:0)

如果您需要删除数据库表中的所有/特定条目,可以通过在admin.py文件中注册模型,通过Django管理面板来实现,

首先,输入命令

创建超级用户
python manage.py createsuperuser

在您的admin.py文件中

from django.contrib import admin

admin.site.register(YourModelName)

现在,在超级用户的django管理面板中登录并删除所需的条目。我希望这会有所帮助。