I have API - python script (using Flask and SQLite) which works with database with 3 tables.
Table Comany has relationship 1:N with table User. And table Company has relationshipt 1:N with table Keyword.
Now, if I will delete some company, I expect it will also delete all users who belong to company, as well as all keywords.
I have found, I have to turn on FOREIGN Keys, using these lines
#event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
if type(dbapi_connection) is sqlite3.Connection: # play well with other DB backends
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
However it will still only delete company, and foregin keys in rows of users as well as keywords of this company stay NULL.
E.g. Table User
ID, Name, Pass, FK_company_name
These are lines how I am deleting company
...
company_id = request.args.get('company_id')
company = Company.query.get(company_id)
db.session.delete(company)
db.session.commit()
...
Do I have to set something else?
The following query retrieves every reservation in the database, but I only want to get the reservations that the current user made. When I run the query in the mysql command line, it works. Why isn't this working in my app?
from flaskext.mysql import MySQL
from flask.ext.login import LoginManager
from flask_login import current_user
...
db = MySQL()
db.init_app(app)
...
cur = db.connect().cursor()
cur.execute("SELECT ReservationID FROM Reservation WHERE user_name=" + "'" + current_user + "';")
reservation_instance = cur.fetchall()
current_user is a User instance. You can't just add it to a string, you need to use it's username (assuming you called the attribute "username").
You are currently open to SQL injection attacks. Never try to insert parameters into a query string yourself. Always use parameterized queries, which lets the driver do the work of building, quote, and escape the query properly.
cur.execute('SELECT ReservationID FROM Reservation WHERE user_name=?', [current_user.username])
The placeholder character (I used ? in the example) depends on the driver. Consider using SQLAlchemy, which normalizes this sort of thing and is much more powerful. There is the Flask-SQLAlchemy to make integration with Flask easier as well.
I have a custom management command to import data from one db and create model instances from it. Basically it is:
class Command(BaseCommand):
def handle(self, **kwargs):
cursor = connections['db2'].cursor()
sql = 'SELECT * FROM table'
cursor.execute(sql)
for row in cursor.fetchall():
my_model = MyModel(*row)
my_model.save()
First I was importing from sqlite to sqlite and all went well. But when I switched to MySQL as my main db, I started getting UnicodeEncodeError, when calling my_model.save(). The caveat is that I have non-ascii symbols in db (namely Russian), but as I get, Django converts all strings to unicode. And yes, both dbs use utf-8.
It seems that bug is due to mezzanine app, I'm using
https://github.com/stephenmcd/mezzanine/issues/1132
I want to do a Django Python MySQL query with WHERE (in sql) being a link generated from a previous query.
Hereby I paste my actual code:
def population(request):
db = MySQLdb.connect(user='xxxx', db='xxxxdb', passwd='xxxxpwd', host='localhost')
cursor = db.cursor()
cursor.execute("SELECT last_name FROM a_population WHERE country='Denmark' ORDER BY last_name")
denominazione_comune = cursor.fetchall();
rows_count = cursor.rowcount
db.close()
counter = 0
return render_to_response('list_last_name.html', {'lastname': last_name}, context_instance=RequestContext(request))
So from this code I get an (un)ordered list of family names. By clicking one of these family names I would like to create another query with the family name clicked as a parameter but I don't have a clue of how to do that.
Thanks a million to whom will give me some input.
I have two questions:
How do I delete a table in Django?
How do I remove all the data in the table?
This is my code, which is not successful:
Reporter.objects.delete()
Inside a manager:
def delete_everything(self):
Reporter.objects.all().delete()
def drop_table(self):
cursor = connection.cursor()
table_name = self.model._meta.db_table
sql = "DROP TABLE %s;" % (table_name, )
cursor.execute(sql)
As per the latest documentation, the correct method to call would be:
Reporter.objects.all().delete()
If you want to remove all the data from all your tables, you might want to try the command python manage.py flush. This will delete all of the data in your tables, but the tables themselves will still exist.
See more here: https://docs.djangoproject.com/en/1.8/ref/django-admin/
Using shell,
1) For Deleting the table:
python manage.py dbshell
>> DROP TABLE {app_name}_{model_name}
2) For removing all data from table:
python manage.py shell
>> from {app_name}.models import {model_name}
>> {model_name}.objects.all().delete()
Django 1.11 delete all objects from a database table -
Entry.objects.all().delete() ## Entry being Model Name.
Refer the Official Django documentation here as quoted below -
https://docs.djangoproject.com/en/1.11/topics/db/queries/#deleting-objects
Note that delete() is the only QuerySet method that is not exposed on a Manager itself. This is a safety mechanism to prevent you from accidentally requesting Entry.objects.delete(), and deleting all the entries. If you do want to delete all the objects, then you have to explicitly request a complete query set:
I myself tried the code snippet seen below within my somefilename.py
# for deleting model objects
from django.db import connection
def del_model_4(self):
with connection.schema_editor() as schema_editor:
schema_editor.delete_model(model_4)
and within my views.py i have a view that simply renders a html page ...
def data_del_4(request):
obj = calc_2() ##
obj.del_model_4()
return render(request, 'dc_dash/data_del_4.html') ##
it ended deleting all entries from - model == model_4 , but now i get to see a Error screen within Admin console when i try to asceratin that all objects of model_4 have been deleted ...
ProgrammingError at /admin/dc_dash/model_4/
relation "dc_dash_model_4" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "dc_dash_model_4"
Do consider that - if we do not go to the ADMIN Console and try and see objects of the model - which have been already deleted - the Django app works just as intended.
django admin screencapture
Use this syntax to delete the rows also to redirect to the homepage (To avoid page load errors) :
def delete_all(self):
Reporter.objects.all().delete()
return HttpResponseRedirect('/')
You can use the Django-Truncate library to delete all data of a table without destroying the table structure.
Example:
First, install django-turncate using your terminal/command line:
pip install django-truncate
Add "django_truncate" to your INSTALLED_APPS in the settings.py file:
INSTALLED_APPS = [
...
'django_truncate',
]
Use this command in your terminal to delete all data of the table from the app.
python manage.py truncate --apps app_name --models table_name
There are a couple of ways:
To delete it directly:
SomeModel.objects.filter(id=id).delete()
To delete it from an instance:
instance1 = SomeModel.objects.get(id=id)
instance1.delete()
// don't use same name
Actually, I un-register the model (the table data that I want to delete) from the admin.py. Then I migrate.
python manage.py makemigrations
python manage.py migrate
python runserver
Then I register the model in the admin.py and do migration again. :) Now, the table is empty. This might not be a professional answer, but it helped me.