Renya K
Renya K

Reputation: 63

Django rest framework api with existing mysql database

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.

Upvotes: 4

Views: 7560

Answers (2)

krflol
krflol

Reputation: 1155

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.

Upvotes: 2

Sushrut Ashtikar
Sushrut Ashtikar

Reputation: 21

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

Upvotes: 2

Related Questions