Change in model not detected - python

I added this module to my application: https://github.com/tomwalker/django_quiz.
The module has a submodule named quiz, which has a model class called Question.
I want to change that class so that it corresponds to a user so I added this to the submodules's models.py:
user = models.ForeignKey(
User,
verbose_name=_("UserId")
)
I am now trying to generate the corresponding database migrations.
However, when I run python manage.py makemigrations nothing happens.
Why is that the case?

You claim some migrations were made. Well probably Foreign Key was created successfully. If you added some parameters to Foreign Key, this might not be needed to migrate database, but Django will take that change into account.
It is probably your case. Try to run python manage.py migrate quiz and see if it works as you wanted in the first place. If not, let us know what setting is missing.

Related

django table has no column named Exception

Git Repository
Request to guide me on what to do.
I work on an e-commerce website with the help of Django. and I'm a beginner in Django
The following image provides a table of my database. It helps to add a product
Shows me an error in the browser. This error shows me when I add a product inside the admin panel. It helps to add a product but when I add the product the following error occurs.
An error occurred while migrating
Request to guide me on what to do.
After first migrations,if you add any field that can not be null you must provide a default value. Your desc field is not nullable, so you must add default='some_value' inside your desc field.
Do you have the table ready and set up? Because the error says, that there is a table named shop_product, but it does not have a column named product_name.
So the structure of your table would get us closer to the solution of your problem.
Edit:
I have just seen, that you supplied your Git repo. I looked at the database and what I wrote above holds true. Your shop_product table has no columns. I did not look through your code to see if it would be set up automatically, but I suppose you were supposed to create the columns by hand, right?
Take a look at here (Django Migrations Workflow)
I've seen your migrations folder on your Github repo and there was no sign of any of the fields you mentioned.
Every time you add fields to your models, you need to run following commands in terminal
python manage.py makemigrations <app name>
python manage.py migrate
These commands are going to modify your tables.
Please markdown your question instead of putting a picture from your code.
Check this out: How do I ask a good question?
EDIT:
In your Product model, there is a field named desc. You need to set a default value for it; Otherwise, you need to update the records in your database manually.
desc = models.CharField(max_length=300, default='')
After you do that, this error will happen to the pub_date field too. So, if your current Product objects in your database are not important, you can simply delete the database file db.sqlite3 and delete your migrations file from this address shop/migrations/0001_initial.py and try the migration commands again.

Django ORM migration giving "ValueError: invalid literal for int()" on IntegerField

Step by step, here is how I got to where I am now...
I attempted ran the command python manage.py migrate after changing my Order table in my database to include include flowertype = IntegerField() and was told that I couldn't move forward with the migration until I either a) set a default value to the IntegerField(), or b) let django set it for me. I chose a and set the default value to 'something' just to get the error out of my hair.
Realizing that I shouldn't have put a string into an IntegerField(), I have tried the following to fix this issue.
1) tried to reset models.IntegerField() to models.IntegerField(default='1')
2) tried to reset my sql database using django-reset and it gave me a ton of errors like `ImportError: cannot import name sql_delete
3) commenting out my Order model and then running makemigrations & migrate to no avail.
The migration failed in python, so it never made it to the database. You should leave everything as is, and go into the migrations/ folder and delete the migration which adds the flowertype field (it's going to be the most recent one). Then run python manage.py makemigrations again, but make sure you have flowertype = IntegerField(default=1) (not default='1') set in the model definition.
EDIT for further explanation:
When you run the command makemigrations, django inspects all of your model definitions in python and compares them against what is in the database. If the two don't match, django will create a migration file which will update the database to reflect the model definitions as they are defined in your python code. This is what the migrate command does, it runs all of the new migration files.
So the first time you ran makemigrations, a migration file was created which added a column to the Order table, and tried to set the value of every row to 'something'.
This immediately failed, since it was trying to put a str into and int field.
Since it failed, unless you delete the file, any and everytime you run migrate, django was going to keep trying to run that script. There were two options 1) You could've just went in and edited the migration file by hand, or 2) You can just delete that migration file and re-create it once you have your model definitions fixed.

Rename Django model

I've just started working with Django, and when setting up my models and db I picked a name which I would like to change now. Is it OK to just edit models.py (rename the class), then run makemigrations and migrate on it? I have a table set up in the db (SQLite), but no entries yet.
I'm new to database migration too. Does this cover what I want to do?
Thanks.
After renaming of model in the models.py, run makemigrations. The question should appear "Did you rename the xxx model to yyy? [y/N]" Press y and it will be enough in your case.
UPD:
In general, you should run makemigrations and migrate every time when you change code in models.py. You should manually edit migrations files (created by makemigrations) only in few cases, when the Django isn't smart enough to understand what you want to do.

Django 1.6: Clear data in one table

I've a table name UGC and would like to clear all the data inside that table. I don't want to reset the entire app which would delete all the data in all the other models as well. Is it possible to clear only one single model? I also have South configured with my app, if that would help.
You could use raw SQL :
cursor.execute(“DROP TABLE UGC”)
or you could just use the ORM directly inside a Django shell :
UGCModel.objects.all().delete()
That would erase the data (not the table, though), so you have to be careful :)
Another way (for completeness and to make use of South) would be to comment out the model in your models declaration, migrate and then put it back again (assuming there are no models with a reference to it.)
HTH
In the admin interface, you can go to the list page for that model, then you can select all models and use the Delete selected ... action at the top of the table.
Remember that, in whatever way you delete the data, foreign keys default to ON DELETE CASCADE, so any model with a foreign key to a model you want to delete will be deleted as well. The admin interface will give you a complete overview of models that will be deleted.
Faced such issues today with django 2.0.2 because i created my model with
class Front(models.Model):
pass
and migrated it but when i later updated the model, i couldn't run
python manage.py makemigrations because it was saying
You are trying to add a non-nullable field 'update' to front 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
with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
What was my solution?
I choose option 2 which is to quit
I commented out the troublesome model/table which is Front in my case
I ran python manage.py makemigrations which deleted the troublesome table/model
I uncommented my model and ran python manage.py makemigrations again which recreated the table/model and finally
I migrated my changes with python manage.py migrate and everyhing was resolved!
Note: Be careful with the above instruction cause it will delete all references/foreign keys to the table/model with on_delete=models.CASCADE which is the default!
Django 3.1.14
If you're interested in doing it on the command line, and you'll be doing this type of cleaning of your db frequently, I do this:
# project_name/app_name/management/commands/clear_test_models.py
from django.core.management.base import BaseCommand
from django.apps import apps
keep_models = ['KeepModel0', 'KeepModel1']
class Command(BaseCommand):
"""
clear all in app_name app except listed in keep_models list
"""
help = 'clear all models except those listed in keep_models list'
def handle(self, *args, **kwargs):
my_app = apps.get_app_config('app_name')
my_models = my_app.get_models()
for model in my_models:
if model.__name__ not in keep_models:
model.objects.all().delete()
To run on the command line:
DJANGO_SETTINGS_MODULE=app_name.settings.local python manage.py clear_test_models

Migration: Creating UserProfile in Django/MySQL

I have created a UserProfile field in order to add a favorites functionality to my site. Using Django's recommendation, I created a UserProfile model as follows at the bottom
Unfortunately, I already had the rest of my database created, and so I need to either use a migration utility or manually edit my database. However, I do not have sufficient permissions to utilize a migration utility, so I have to edit the database directly, and am struggling to do so.
This answer is similar to what I want to accomplish, but I can't quite get the syntax to work in my case.
MySQL - One To One Relation?
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
favorites = models.ManyToManyField(Media, related_name='favorited_by')
In my experience, the best migration utility is South. Once you've installed and added it to your settings, you'll need to create initial migrations for your existing modules using
./manage.py schemamigration --initial my_module,
which will include the one containing your UserProfile model, then from there you can migrate using
manage.py migrate my_module.
The real power in using a utility like this is portability and reversibility. You can migrate forward and backward as needed, and you'll be able to bring your schema to virtually any SQL database without all the fuss of rebuilding using SQL directly.
I would certainly agree with Steves recommendation to use South.
However if you for some reason wouldn't want to, you can issue the following command:
python manage.py sql <appname>
This will output the SQL statements which django will use to create your tables. This can then be used to manually modify the database.

Categories