Reputation: 63
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
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
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
class Meta:
db_table = "RandomTable" #your existing mysql table name
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