Universal SQL analog for ORM
ALTER TABLE `tablename` AUTO_INCREMENT =1;
Model TestData
TestData.objects.all().delete()
id = [1 .. 53]
import data from csv_file
id = [54 ... ]
del data ...
Django Main functional for reset work fine
python manage.py sqlsequencereset test_app
or code run command (work)
from django.core import management
management.call_command('sqlsequencereset')
Is it possible to reset AUTO_INCREMENT with Django ORM, without management call?
Related
I am using Django models to create a PostgreSQL-DB. I have a DateTimeField where I would like to set the current timestamp as default value. I am aware of multiple sources suggesting how to do this. However, when I inspect my DB outside of Django, the default timestamp doesn't show up.
Approaches I have tried:
1.
created_at = models.DateTimeField(auto_now_add=True)
from django.db.models.functions import Now
...
created_at = models.DateTimeField(default=Now())
from django.utils.timezone import now
...
created_at = models.DateTimeField(default=now)
What I would expect is for the PostgreSQL database to show:
TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
What It shows is timestamp with time zone not null but no default value. Any ideas on how to do that would be greatly appreciated.
However, when I inspect my DB outside of Django, the default timestamp doesn't show up.
That is correct, Django itself manages the default values. Not the database, Django also manages the ON DELETE trigger, not the database. This gives more flexibility. For example you can pass a callable to the default like you did with default=now. This callable can perform sophisticated actions to determine the default value like making extra queries, API calls, file I/O, etc. This is not possible with a default at the database side.
You can make a data migration file and manually alter the table. You can initialize a data migration with:
python manage.py makemigrations --empty app_name
next you can alter the file it has generated and specify a default with:
# Generated by Django 3.1 on 2020-12-16 17:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app_name', 'migration_name'),
]
operations = [
migrations.RunSQL(
'ALTER TABLE table_name ALTER COLUMN created_at SET DEFAULT CURRENT_TIMESTAMP';
)
]
The advantage of doing this is that Django manages the migrations, and it will thus migrate the databases that have not been migrated and thus add a default value.
im learning django 1.8.x. In older django(1.4) we can view sql query like
"Begin;
create table "article_article" ("id" integer NOT NULL PRIMARY KEY,
...
...
);
COMMIT"
for creating model object of an APP called article by running :-
python manage.py sql <appname>
is there a way so that i can view sql query used to create model objects for that app in Django 1.8.9 ?
cheers
You can see the SQL per migration now. So assuming it's the first sync (i.e. syncdb in older Django):
python manage.py sqlmigrate <appname> 0001
I have an application 'registration' in which I am trying to add an extra field in Django auth groups. I have successfully implemented it using monkey patching. However, when I post this application to someone else and they run 'migrate', the build fails stating the reason that the newly added field does not exists. The reason being that when I created the migrations, the migration files were not created in my 'registration' application, instead, they were created in the Django.contrib.auth application.
How can I get past this problem?
I solved it by adding a dummy migration file in my application - 'registration'. Inside this migration, I created the column manually by executing an SQL Query so that the build does not fail. I'll post the code here.
def check_and_add_column(apps, schema_editor):
import sqlite3
conn = sqlite3.connect('db7.sqlite3')
cur = conn.cursor()
result = [True for i in cur.execute('PRAGMA table_info(auth_group)') if i[1] == 'is_auto_assign']
if not result:
cur.execute('ALTER TABLE auth_group ADD COLUMN is_auto_assign BOOLEAN DEFAULT FALSE')
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
]
operations = [
migrations.RunPython(check_and_add_column,),
# If you need to run SQL directly from here
# migrations.RunSQL("ALTER TABLE auth_group ADD COLUMN is_auto_assign BOOLEAN DEFAULT FALSE"),
]
Currently programming in Python Django 1.4. In my files I have written CREATE TABLE functions for productos and clientes to be created in the MySQL database. When I checked with python manage.py sqlall ventas (ventas being the parent directory of productos and clientes), it outputs that snippet of code. However, when I tried to access them under localhost admin, I got the
1146, "Table 'demo.ventas_cliente' doesn't exist" error. And these 2 tables do now show up in MySQL.
Initially I had dropped these 2 tables because there were some DB errors. I ran syncdb again but does not seem to retrieve those 2 tables. What seems to be wrong?
I strongly suggest you don't type MySql commands directly, this may throw you many errors in the future. To create tables in Django you must create models. For example:
1) In ./Yourproject/apps/yourDBName create __ init __.py
2) in settings.py under "installed apps" add your new app. Example: yourproject.apps.yourapp
4) execute "python manage.py runserver"
5) create models.py into your new app
6) now you can create your models like that:
class myTable(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
7) if you want to access your new table from the admin, create admin.py in your app and type:
from django.contrib import admin
from models import myTable
admin.site.register(myTable)
#here, you can add more tables to the admin in the future
also, if you need to use foreign keys:
class parentTable(models.Model):
idParent = models.AutoField(primary_key=True)
parentName = models.CharField(null=False)
class childTable(models.Model):
idChild = models.AutoField(primary_key=True)
MyParentName = models.ForeignKey(parentTable, to_field='parentName')
childName = models.CharField(null=False)
MORE INFO: https://docs.djangoproject.com/en/dev/topics/db/models/
I am using django and postgresql db to develop my project, the db has 3 schemas. And I am writing raw quires using connection string to fetch data and insert data into tables.
Example:
from django.db import connection
query = "select * from schema1.records"
cursor = connection.cursor()
cursor.execute(query)
output = cursor.fetchall()
Like way I am using in my all views.
I wanted to write test cases to my views, so i need to generate fixtures to test my views, how to I generate fixtures for schemas and tables. Please help.
Note: I did not write any models i just used raw queries in my whole project.
Run:
manage.py dumpdata help
This will show how to use loaddata to generate fixtures.