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
Related
i'm happy with django built in user/auth , i just want to add some fields to it and change table name (mostly the last one , i can use another table for custom fields )
so i searched around and apparently we can use subclass as suggested on Rename Django's auth_user table?
So i have to start a new app and use it's model to as a subclass for AbstractUser or there is another way? (After all i just want to use it's model and other parts of app are useless )
anyway i created a new project / started app called customuser and in its model i have this code
customuser/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class customuser(AbstractUser):
class Meta:
swappable = 'AUTH_USER_MODEL'
db_table = 'customuser'
i ran makemigrations AND migrate ... it's done successfully
but atill the tables with default name was created in database as you can see below ... am i missing something ?
To use a custom user model, you need to set the AUTH_USER_MODEL setting in your settings module.
Note that you don't need to set swappable = 'AUTH_USER_MODEL'. This is an undocumented and private attribute, and is probably better left untouched.
Quite frankly if you're still in the position to do it, i'd just start a new app. It says in the docs that this decision is best made before starting your project because its a pain in the ... its hard.
If you intend to set AUTH_USER_MODEL, you should set it before creating any migrations or running manage.py migrate for the first time.
The solution otherwise is to dumpdata from the database, and manually tweak it so any reference to the user class in your dump file is replaced with your new user class. then you need to create some migrations to change the schema.
So it is doable. its just much simpler to start from a fresh project.
Django allows you to override the default User model by providing a value for the AUTH_USER_MODEL setting that references a custom model
AUTH_USER_MODEL = 'myapp.MyUser'
This dotted pair describes the name of the Django app (which must be in your INSTALLED_APPS), and the name of the Django model that you wish to use as your user model.
A full example of an admin-compliant custom user app can be found on the Django Project website.
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.
I have an existing database that I'm trying to access with Django. I used python manage.py inspectdb to create the models for the database. Currently I'm able to import the models into the python shell however when I try to access any of the actual objects in any way, I get this error OperationalError: (1054, "Unknown column 'some_table.id' in 'field list'"). I see that the table in the database in fact does not have an id field. How can I fix this? Do I need to update the managed field in the Meta class and run a migration so it can create this field automatically?
From the Django documentation: This feature is meant as a shortcut, not as definitive model generation. See the documentation of inspectdb for more information. (Reference: https://docs.djangoproject.com/en/1.8/howto/legacy-databases/)
You're going to need to manually clean up the models and migrate. The line you'll have to add for adding the "id" field is:
id = models.IntegerField(primary_key=True)
Warning: I'd definitely create a copy of the database to toy with, rather than the original. This will likely take you some trial and error to get right. After you're absolutely sure you have it right, you can changed Managed=True, but be VERY careful!
I'm trying to extend the User model of a django app, but I keep getting the error:
OperationalError at /admin/auth/user/3/
Exception Value: no such column: subjects_subject.user_id
My Code:
#subjects/models.py
from django.contrib.auth.models import User
from django.db import models
class Subject(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length=100)
models.signals.post_save
#_admin/admin.py
from django.contrib.auth.models import User, Group
from django.contrib.auth.admin import UserAdmin, GroupAdmin
from .extended_admin import new_admin
from django.contrib import admin
from subjects.models import Subject
class SubjectInline(admin.StackedInline):
model = Subject
can_delete = False
verbose_name_plural = 'subject'
class UserAdmin(UserAdmin):
inlines = (SubjectInline, )
new_admin.register(User, UserAdmin)
new_admin.register(Group, GroupAdmin)
I have pretty much copied Django's own documentation word for word. Any help would really be appreciated!
EDIT:
I also wanted to say that I have ran syndb and flush
I had the same issue and here are the steps I took to solve it. You did not specify the database you are using but in my case I am using MySQL. From Django docs here https://docs.djangoproject.com/en/1.8/topics/migrations/#mysql it seems sometimes creating the tables fails. I had a table called 'administration' and that kept failing to detect any changes.
Here is what I did:
Remove migration directory from my app. This was so as to create new migration schemas
Rename the directory. I renamed my directory from 'administration' to 'donor'. For some weird reason this seemed to fix the issue. I am not entirely sure why but could be 'administration' is a key word in either MySQL or Django
If both steps do not work, you might have to manually add the changes as directed on the django docs. Even easier, you can drop the existing table if its empty and recreate it. (WARNING! Please only do this if the table is empty otherwise you risk losing all your data)
All in all, there seems to be no outright reason as to why this could be happening at the moment. My trial and error approach seems to have fixed it.
Did you solved this problem?
I had the same issue , after different trying , I solved this. I'm using sqlite3 .
it seems like the when you first migrate , there is something wrong with the database table (I don't know what this problem caused by , so you raise the error : no such column: subjects_subject.user_id)
if you remove the migrations directory , and re-migrate , that will not solve this problem , because Django keeps track of all the applied migrations in django_migrations table.Migration was faked because the table already existed (probably with an outdated schema)SO I delete all the rows in the django_migrations table.
Here is what I did:
1.remove all files in migrations directory in my django app
2.using python manage.py dbshell , then DELETE FROM django_migrations WHERE app='your-app-name or DELETE FROM django_migrations WHERE ID='your-first-migrate
3.then python manage.py makemigrations python manage.py migrate
Successful!
I've created a model in one of my apps which works fine. However, I needed to add a new field. I did this, and used manage.py reset <appname> to drop the tables and add them again. This process went fine - the new field appears in the database. However, I can't get the field to show up in the admin interface, nor in the custom model form I've created. Because I haven't given it a default value (and don't want to, nor should I need to) I can't use either method to add a row into the database. Any ideas?
Model snippet:
use_balance = models.BooleanField()
Have you restarted your server?
By any chance, did you forget to update your ModelAdmin definitions?