In the document, I can define a table in the models.py.
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
Run python manage.py makemigrations and python manage.py migrate to create a new table in the database.
If I want to create a new table when do something in the views.py, is it possible?
For example, I want create a personal table for some new member when he/she register a new account.
this is not suggested, standard and neither possible. the tables will be referenced over migrations and will be created by model classes. any table which violate these rules will make you trouble in the future
Related
I'm new to Django and I am trying to use a mysql database created and filled with data by someone else
I created a model with the same name as the table I want to get data from, my models is as follows
class Study(models.Model):
study_name = models.TextField(default='Unknown')
description = models.TextField(default='Unknown')
language = models.TextField(default='Unknown')
number_of_years = models.IntegerField(default='0')
database connected but when I go to admin I don't see the data there
Please help me with this
A step by step solution would be:
get the name of the table containing your data, I'll call it study_table
make sure you know how the table was defined so you can match it with django model definition. Connect to the database with a MySQL client and run the following query:
DESCRIBE study_table;
based on the table name, column types and column names, define your model to match everything. Django models do a lot of automated naming so you have force the naming to make sure your model matches your database. Principles are:
Specify the table name as a meta option.
Create fields with names matching column names and field types matching column types. Taking an example from your code, the field study_name should match a column with the same name in the table study_table.
class Study(models.Model):
study_name = models.TextField(default='Unknown')
description = models.TextField(default='Unknown')
language = models.TextField(default='Unknown')
number_of_years = models.IntegerField(default=0)
class Meta:
db_table = study_table
Side note: your IntegerField has a default as a string '0'.
making sure the app (I'll call it study_app) containing your model is enabled, the database is configure properly in your django settings, try to access data from the admin shell (python manage.py shell):
>>> from study_app.models import Study
>>> Study.objects.first()
This should return an answer, if it does not, your model doesn't match the database data.
to make accessing the data easier, create an admin page as suggested by #iklinac. You can now read, edit your data through your browser.
A few suggestions you could consider:
study_name should probably be a models.CharField(max_length=255) or similar
description should be allowed to be empty models.TextField(blank=True)
language should probably be a models.CharField with a choices option.
You should create ModelAdmin instance for your model
The ModelAdmin class is the representation of a model in the admin
interface. Usually, these are stored in a file named admin.py in your
application.
from django.contrib import admin
from myproject.myapp.models import Study
class StudyAdmin(admin.ModelAdmin):
pass
admin.site.register(Study, StudyAdmin)
If you have a MySQL database with tables of data that don't have models created yet, you can use the dumpdata command to automatically generate the models:
https://docs.djangoproject.com/en/3.0/ref/django-admin/#dumpdata
Then, you can register those models in the Django admin. dumpdata should only be used as a starting point, since they are auto-generated and won't contain many of Django's data integrity features.
Good luck!
I'm currently working on a project with Django, I have designed a model like
Class Item(models.Model):
id
name
...
And I've already had a sqlite database with data like
Id, name, ...
1, a, ...
2, b, ...
Now, the question is how I can push this database to django? Thanks
You usually don't create any databases tables in the database per se, you just need to create the Django models and then run and apply the migrations. So, for instance, if you have the following model:
class Item(models.Model):
name = models.CharField(max_length=255)
You just need to go to the terminal and type
python manage.py makemigrations (This will create a migration file)
python manage.py migrate (This will create the actual tables/columns in your database)
If you then open a shell:
python manage.py shell
and create an object via Django:
from yourapp.models import Item
Item.objects.create(name='Hello')
That Item should be saved to your DB.
We are trying to makemigrations and migrating the app level model to respective databases using database router.
We have one model file in one app pointing to one database and same structured models with table name with some tables added are being created in other app then intermediate table name is creating error.
Error : master.LegalTbl.legal_field_name: (field.E340) The field's intermediary table 'tbl_legal_tbl' clashes with the table name of 'user.LegalTbl'.
I'm not sure may be it could work:
delete the migration file that has conflict.
add Class Meta to your model which name you want to change
meta class have one attribute called db_table write table name
Now you can run makemigrations and migrate, it will solve your conflict i guess
Whenever I make migrations, Django automatically attaches the name of my application to database tables. For example, if I have application myapp and there is a model named Model1, then after migrations the database table name will be myapp_model1.
I don't need app name along with table name. If someone knows how to change it then please help me.
My advice is to let Django choose the table names automatically. Having the application name as a prefix means that you can have two models with the same name in different applications, but their database table names will not clash.
If you really want to change the table name, you can use the db_table option to set the table name in the database.
class MyModel(models.Model):
name = models.CharField(max_length=50)
...
class Meta:
db_table = 'mymodel'
This might be tricky if the database tables have already been created. To avoid problems, I would only set the db_table option for a new application.
Regarding Django & Python:
The Error:
Exception Type: DatabaseError
Exception Value:
column objects_thing.name_id does not exist
LINE 1: ...s_thing"."created", "objects_thing"."modified", "objects...
In my manage.py sql objects
CREATE TABLE "objects_thing" (
otherstuff,
otherstuff,
"name_id" integer NOT NULL REFERENCES "profiles_name" ("id"),
otherstuff,
);
So it clearly exists.
I've ran syncdb.
Why am I getting this error? And how do I go about fixing it? (I'm a newbie to all of this) Thank you in advance for the help.
EDIT:
Thing Model:
class Thing(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
name = models.ForeignKey(Name)#The name for this thing
current_allocation = models.DecimalField(max_digits=13, decimal_places=2, null=True, blank=True)
target_allocation = models.DecimalField(max_digits=13, decimal_places=2, null=True, blank=True)
placeholder = models.ForeignKey(Entity, null=True, blank=True, on_delete=models.SET_NULL)
avatar = models.ImageField(upload_to='avatars/thing/', null=True, blank=True)
syncdb doesn't change existing tables in your database, so if you run that, and then change your model, your model is now out of sync with the table it represents. Running syncdb again will not fix that.
You either need to use something like south to do a migration, delete the table from your DB so that syncdb will recreate it, or manually run an ALTER TABLE on your DB.
EDIT (greater detail)
When you create a subclass of Model in models.py, it acts as a representation of a database table, but doesn't automatically have a database table. You get that by running python manage.py syncdb. Django, then, looks through all your models.py files, generates the SQL required to actually create a table like that and then runs it on your database. The end result is that you end up with actual database tables that are tied to your models.
However, syncdb only creates tables. It does not alter them. So, if you go and change one of your models (add a field, change the name of a field, etc.), nothing has happened at the database level. Running syncdb again will not help, either, because there's no new tables to create. You have to somehow get the table to match the model and vice versa, though, so that's where your options come in:
Use South (link above). South enables you to create migrations, so when you change something on your models you can run:
python manage.py schemamigration --auto yourapp
And it will generate code that will alter the table to match your model. You then need only apply the migration with:
python manage.py migrate yourapp
And you're done. The table now matches your model and all is right in the world again.
You can manually delete the table from your database. You wouldn't want to do this in production because all the data in that table will go along with it, but in development it shouldn't be a problem. After the table is gone, you can then run:
python manage.py syncdb
Because, the table no longer exists, Django will create it, but it will create it based on your current model's state. The net result is the same, your model and table match, so you're good to go.
You can manually alter the table. This requires that you figure out what SQL needs to be applied to change the table to match your model. You run this SQL on your database, and then the table is in parity with the model.
The point is that somehow, someway, you must update the table to reflect any changes you make to your models. The model isn't the table, it's just a programmatic representation of it.
The column might not necesarrily exist. The sql command just shows the sql used to create it, It is based on your current model. You could delete the table and re syncdb or manually add the column. https://docs.djangoproject.com/en/dev/ref/django-admin/#sql-appname-appname
I think there is a little confusion regarding the django Model and the actual database table
The django model is just some python code. It is a python object that is connected to a sql table. The database backend is specified in settings.py. The database contains the actual table. The error you are encountering is indicating that the python model is not the same as the actual database table.