Learn how to use Django's DB without a runserver.

Asked 2 years ago, Updated 2 years ago, 60 views


without launching the Webserver (without running python3 manage.py) I only want to use the OR mapping and migration capabilities of Django's database, but I'm stumbling.
There seems to be an order to define django.setup() and model class. Could you tell me how to solve this problem?

[Reference Site]: https://logixsquare.com/techblog/django_models_only/

】What I did <:
# Create/activate a virtual environment
python3-m venv venv
source venv/bin/activate
# Installing Django pip3 install django
# Create a Django Project
mkdir hello worldproject
cdbookproject
# Create Django app (no need?)
django-admin startproject hello
# ./Application name/test.py contains the following code

[Error Contents]
When you change the INSTALLED_APPS and define a model class, the following error occurs:
'hello.tests' does not contain a'SampleModel' class.

import sys

# initial configuration
sys.path.append('./helloworldproject')

if__name__=='__main__':
    from django.conf import settings
    settings.configure(
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': './db.sqlite3',
            }
        },
        # INSTALLED_APPS = ['hello.tests.SampleModel'] # ← Error when commenting out here and below SampleModel class.
    )

    import django
    django.setup()

    # model definition
    # from django.db import models
    # Class SampleModel (models.Model):
    #     title=models.CharField(max_length=100)# column title
    #     number = models.IntegerField()# column number

python3 django

2022-09-30 11:04

1 Answers

Resolved.

You can now specify 'hello.apps.HelloConfig' for INSTALLED_APPS by adding:

import sys
sys.path.append('.')

The SampleModel class was listed on models.py, mademigrations, migrated.

Thank you.Close.


2022-09-30 11:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.