2

I am using Python3.6 and django 2.0.2, and developing a website for user search in Pycharm. I want to use a legacy database which called User, and had data saved automatically from other source, I won't change the database during the website interaction. Firstly, I configure the database in settings.py as following:

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'legacy_db': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'name',
    'USER': 'user',
    'PASSWORD': 'pass',
    'HOST': 'host',
    'PORT': '3306',
}

}

Then I use the inspect db to create the model file, the command is as following:

python manage.py inspectdb --database legacy_db > models.py

and the generated models.py is as following:

from django.db import models


class User(models.Model):
    username = models.CharField(max_length=16)
    email = models.CharField(max_length=255, blank=True, null=True)
    password = models.CharField(max_length=32)
    create_time = models.DateTimeField(blank=True, null=True)
    id = models.IntegerField(primary_key=True)

    def __str__(self):
        return self.username

    class Meta:
        managed = False
        db_table = 'user'

After that, I used makemigrations appname and migrate appname to migrate the database.

Then I call the model in my views.py as following:

all = User.objects.all()

I don't know how to get the traceback, I can only see the error info in debugging mode, the error is showing as

all: unable to get repr for <class 'django.db.models.query.QuerySet'>

beside the code. I really searched in Google and StackOverflow but got no luck.

I am new to django, and this is my very first time creating a django website on my own (I walked the steps through of the example website(polls) in django tutorials). So any help would be really appreciated.

tina
  • 31
  • 1
  • 6

1 Answers1

1

I just find the solution, the error is caused by the database routing, cause I didn't add a database routing class, so the query just goes to the default database. And I refer to the urls below to solve this problem. 1. django document

  1. USING DJANGO WITH AN EXISTING LEGACY DATABASE

And from the django document, I also found an easy way to solve this problem, just change the code all = User.objects.all() to all=User.objects.using('archived').all() which will manually set the database to use here.

tina
  • 31
  • 1
  • 6