Create a django project from an existing database - django

I have a n existing MySQL database. I want to create a new django application with that database.
I read that I need to run "syncdb" each and every time when add a new model in django. That time adding a new table in database in <database_name>.<table_name> format. And fetching data from that table.
What is the correct method to fetch data from an existing database in django ?
This is my model:
from django.db import models
class Users(models.Model):
employee_id = models.CharField(max_length=30)
def __unicode__(self):
return self.employee_id

Use the Django model meta options to set db_table and db_column on your Models and Fields respectively. See these links for more info on how to use them:
https://docs.djangoproject.com/en/dev/ref/models/options/#db-table
https://docs.djangoproject.com/en/dev/ref/models/fields/#db-column

Related

How to add new field to a table in django that have "managed=False" because it was generated using inspectdb tool

I'm using an existing mysql database in a new django project, so I generated the models using inspectdb tool.
But now I need to add a new field to a table, I'm doing it by adding the new field to the model and running migrations, but it doesn't work, It doesn't add the field to the table.
Maybe it is because I have managed=False in the meta config of the model, but if I remove it, the migrations won't work, giving me the error "Table5 already exists"
Here is the Model where I'm trying to add the "fields" field
class Table5(models.Model):
names = models.CharField(max_length=150)
fields=models.JSONField(null=True)
class Meta:
managed = False
db_table = 'table5'
How can I achieve this?

Create dynamic model field in Django?

In my models.py my model store contains name, brand_name fields
Now,I want to create new field called brand_type in store model dynamically from Django admin,how can I do this?
Can we change schema of model using SchemaEditor? How?
you can't create model's fields via admin panel
you must create fields in models.py
admin panel is only a convinient way to manipulate your database, but not modifiyng its tables
It requires migration while the server is running. Create brand_type field under your model and set blank=True
In your models.py
class Store(models.Model):
name = ...
brand_name = ...
brand_type = models.CharField(max_length = 40, blank= True, null =true)
In your console
./manage.py makemigrations
./manage.py migrate
Extra Stuff:
If you are interested in Text Choices
or
If you wanna make it more dynamic based on your use case,
create a model called BrandType and link it in Store using
brand_type = models.ForeignKey(BrandType,on_delete=models.PROTECT)
models.py
class BrandType(models.Model):
name = ...
some_other fields=
#... Store model follows
admin.py
# other stuff
from .models import BrandType
admin.site.register(BrandType)
Take away: It is not advisable to modify your models.py file using admin directly it will cause integrity issues and there are better ways to achieve your desired functionality.

How to setup a flexible django models

I'm new to django. What I'm trying to achieve is when the ProductType combobox is changed, the fields changes to its specific fields then the users inputs using those field and entered to the database. My problem is how to create a flexible model that would accept extra fields
from django.db import models
class Product(models.Model):
"""SKU"""
stock = models.IntegerField(default=None)
class ProductType(models.Model):
product_field = models.ForeignKey(ProductFields, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
class ProductFields(models.Model):
"""Fields of ProductType"""
Here's an DB example I'm trying to achieve See Image
SQL database is not suitable for that purpose.
Look for non-SQL databases for ex. Firebase

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.
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
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.

Django - How can Django ORM manage user's uploaded tables in database

My web application allow users to load/create tables in the Postgres database. I know Django ORM needs a model definition in models.py for each table in the database to access it. How can I access the user's uploaded tables in the app without creating a new model definition on the fly each time a new table is uploaded? I was thinking about creating a generic model definition that decompose the table into its components like this:
models.py
class Table(models.Model):
filename = models.CharField(max_length=255)
class Attribute(models.Model):
table = models.ForeignKey(Table)
name = models.CharField(max_length=255)
type = models.IntegerField()
width = models.IntegerField()
precision = models.IntegerField()
class Row(models.Model):
table = models.ForeignKey(Table)
class AttributeValue(models.Model):
row = models.ForeignKey(Row)
attribute = models.ForeignKey(Attribute)
value = models.CharField(max_length=255, blank=True, null=True)
The problems with such a generic model is that every tables are mixed in 4 table (not useful in admin interface) and its really slow to create when you have a lot of rows. Do you have suggestion with this case?
Edit: Could it be viable to use a separate database to store those tables and use a router and manage.py inspectdb to update its models.py each time a user add or delete a table? (like in this post) I wonder what would happen if two users add a table in the same time?
I think you should look into dynamic models like here:
https://code.djangoproject.com/wiki/DynamicModels
or here:
http://dynamic-models.readthedocs.org/en/latest/
Good luck because its not an easy way my friend :)
You'll probably need to use raw SQL queries for doing this.
If the schema of the tables you are expecting are predefined you can use a database router to link some model to a specific table name for each user.