4

How can I create a Django REST Framework API that connects to an already existing MySQL tables instead of creating them through modela.py. My models.py shows something like this:

class Author(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)

    def __str__(self):
        return f'{self.first_name} {self.last_name}'

Instead of this, I need to take data directly from existing tables in MySQL.

cezar
  • 11,616
  • 6
  • 48
  • 84
Renya K
  • 63
  • 1
  • 3
  • 2
    Check this doc: https://docs.djangoproject.com/en/2.0/howto/legacy-databases/ – neverwalkaloner Apr 05 '18 at 09:24
  • Whatever database you have you cab revert create a model, that won't affected to your database. `python manage.py inspectdb > models.py` yes the same @neverwalkaloner has suggested. – Anup Yadav Apr 05 '18 at 09:28
  • now i got it. thank you guys – Renya K Apr 05 '18 at 09:44
  • @neverwalkaloner Why don't you provide a short answer with a simple example? – cezar Apr 05 '18 at 12:43
  • 1
    @cezar I dont think I can describe it as good as official docs:) – neverwalkaloner Apr 05 '18 at 12:49
  • Possible duplicate of [How to change the Column Names of a database created by Django (from models.py)?](https://stackoverflow.com/questions/47676100/how-to-change-the-column-names-of-a-database-created-by-django-from-models-py) – cezar Apr 05 '18 at 12:54

2 Answers2

2

For that you need to define same class name as your table name with meta char field

like for example RandomTable(id INT(10),name varchar(10)) is your existing mysql table then the models.py for it will be

class AppnameRandomTable(models.Model)
    id = models.CharField(db_column="id") #name of column of existing db

inside that you will need to write the fields of your existing table name in meta section

class Meta:
    db_table = "RandomTable" #your existing mysql table name 

time saving hack just create a class in models.py and on terminal run "python manage.py inspectdb" you will automatically get all the column names from there.

You can just copy and paste names from there , because for reading and writing on columns you need to define their variables in your class even if the table is existing mysql table

Mohd
  • 5,523
  • 7
  • 19
  • 30
2
python manage.py inspectdb > models.py

If you run that command it will create a models.py in the project's root directory. Once you've done that you can either move it directly into the project or create a models folder and break it down into areas of concern from there. You will likely have to do the work of adding related_name = 'foo' to a lot of fields that have relationships with other models. That can be time-consuming but it works.

krflol
  • 1,105
  • 7
  • 12