ProgrammingError while opening admin table - python

I am using django with postgres database.
When loading the admin,clicking on Course Table, I get a classic error:
ProgrammingError at /admin/user_profile/course/
relation "user_profile_course" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "user_profile_course"
I tried makemigrations, and migrate it again but no success.
Would you please help me how to handle it?
My models.py looks like:
class Course(models.Model):
name=models.CharField(max_length=30)
number_of_sessions=models.IntegerField()
student=models.ManyToManyField(User, through='Registration')
Edit:
I removed the migration folder, and make migrations again.
in the 0001initial.py the dependencies looks like:
dependencies = [
('auth', '0007_alter_validators_add_error_messages'),
]

It looks like you've removed already applied migration from your migrations folder and re-created it with different model state (with extra model Course).
That will create situation when actual structure of your database is different than state that should be after applying your migration.
Now you can either fix your migration or fix your database structure.
To accomplish first possible fix, you need to check your current state of database and compare it with your migration file. If there is something different in your migration file, simply change it to reflect your database structure.
If you don't know how to edit migration file, you can change your models to reflect database structure, remove your migration and then create it again using makemigrations.
After fixing your migration file, generate second one, just running makemigrations with having desired models structure in your models files.
For second solution, check what's inside your migration file and edit your database structure to reflect that.
And remember, do not ever delete or change already applied migration, unless you really know what you're doing!

Related

Django - delete M2M field but keep join table

is it possible to remove an M2M field from a model and keep the joining table?
context:
I am trying to add through model to existing M2M field like described in this post
But doing it simply like this will result in a production app crash when accessing the old table during deployment - short window between migration and code update, when old code will try to access a new database for a few moments - without the old table in it.
You can use --fake flag when running manage.py migrate. That will make a migration file that says the model field has been removed and mark it as applied in the database migration table, but not actually execute the SQL to remove the corresponding tables etc. Read more here

No model tables are created for a Django migration

I have searched other articles (like this one) for a solution, but nothing has helped so far...
I realized while working on my project that I needed to alter the model, changing a primary key to an AutoField rather than use a custom field. I knew this would cause a lot of issues since I have quite a few ForeignKey fields, so I wanted to drop all of my tables, clear out the migrations, and just let the migrations re-generate all of the the tables. The problem is that even though I dropped all of the tables (and eventually the whole database, due to the django_migrations table and any other latent data), cleared out all of the project/app/migrations directories, when I run manage.py makemigrations/manage.py migrate, it only creates the built-in tables (the auth_* and django_* tables) and none of my model tables get recreated.
Where else do I need to clean up in order to be able to start over with a fresh database model? I thought that clearing out the migrations directories would be sufficient, but there's something else I'm missing.
Thanks.
If you have deleted the migrations folder for an app, you have to specify the app name to create the initial migrations:
./manage.py makemigrations myapp

Django: Quickly deal with adding non-nullable field

When developing models I quite often get the non-nullable field error when running makemigrations:
You are trying to add a non-nullable field 'user' to randommodel without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option:
Almost all the time when I get this error I'm quite happy to delete the data in that table (it's normally only a couple of test entries while developing) and it would be more efficient to just delete it rather than determine what a suitable default would be.
However currently I don't have a suitable method for doing this and end up flushing the database and/or deleting the migrations, which is pretty heavy handed but works.
What's the best way to delete the data just in that model/table to remove the error? (Would it be via shell/shell_plus?)
Model:
class RandomModel(models.Model):
user_details = JSONField(unique=True)
user = models.ForeignKey(User)
Even if you have deleted all the records in that table, when running makemigrations, you'll be asked to provide default values again. This is because you're making a new migration file for an existing table.
One solution I can think of is to tell Django that you're starting that app_name over again by running migrate app_name zero. This will unapply all migration files that have ever been applied to your database.
Then delete all the migration files in your app_name. And run makemigrations again. This would create a new initial migration file. Then you just apply it to your database with migrate.
As you've said you don't mind deleting your data. This is even better. You don't have to even delete any record. It will just create a new table with the same name with all the new fields and with 0 record.

Edit database outside Django ORM

If one is using Django, what happens with changes made directly to the database (in my case postgres) through either pgadmin or psql?
How are such changes handled by migrations? Do they take precedence over what the ORM thinks the state of affairs is, or does Django override them and impose it's own sense of change history?
Finally, how are any of these issues effected, or avoided, by git, if at all?
Thanks.
You can exclude a model completely from the django migrations, and then you are responsible to adjust the schema to the django code (or the django code to the existing schema):
class SomeModel(models.Model):
class Meta:
managed = False
db_table = "some_table_name"
name = models.Fields....
Note that you can't have it both ways, so migrations are preferred when possible. You can always define a custom SQL migration, that will save the need for external changes. However, sometimes you do need to handle the schema elsewhere instead of migrations, and then use managed=False
The migrations system does not look at your current schema at all. It builds up its picture from the graph of previous migrations and the current state of models.py. That means that if you make changes to the schema from outside this system, it will be out of sync; if you then make the equivalent change in models.py and create migrations, when you run them you will probably get an error.
For that reason, you should avoid doing this. If it's done already, you could apply the conflicting migration in fake mode, which simply marks it as done without actually running the code against the database. But it's simpler to do everything via migrations in the first place.
git has no impact on this at all, other than to reiterate that migrations are code, and should be added to your git repo.

How to change a sqlite table column value type from Django model?

I created a table before I code the Django app and now I merged both the app and the table with following command python manage.py inspectdb > models.py. However after some while I really need to change the value type of one of the column. Is it enough to chage it through the model file or do I need some additional steps?
If you change a field in a Django model, Django itself doesn't know how to update your database accordingly (syncdb only add tables from new models).
You have two options:
manually create your database tables;
use a migration tool like South that detects and generates migration files from changes made to your models;
I recommend the second option as it's programmatic, more error-proof and makes your life easier when you need to go back and forth between database schemas.
There is an easy way to do this. (in Django 2)
After making the necessary changes to the model.py file of your app, run command:
python manage.py makemigrations - This will generate a new file in migration folder of your app.
python manage.py migrate - This will apply those edits on actual databse.
To check if the changes have been applied, run command : .schema <tablename> in your terminal, after entering the sqlite command-line program.

Categories

Resources