How can I see the raw SQL queries Django is running?

See the docs FAQ: “How can I see the raw SQL queries Django is running?” django.db.connection.queries contains a list of the SQL queries: from django.db import connection print(connection.queries) Querysets also have a query attribute containing the query to be executed: print(MyModel.objects.filter(name=”my name”).query) Note that the output of the query is not valid SQL, because: “Django … Read more

Django – how to specify a database for a model?

You can’t specify a database for a model, but you can define it in a custom DB router class. # app/models.py class SomeModel(models.Model): … # app/dbrouters.py from app.models import SomeModel … class MyDBRouter(object): def db_for_read(self, model, **hints): “”” reading SomeModel from otherdb “”” if model == SomeModel: return ‘otherdb’ return None def db_for_write(self, model, **hints): … Read more

How to view database and schema of django sqlite3 db

Goto the folder where the database is and then sqlite3 db.sqlite3 Then .tables or .schema depending on what you want. Instead of invoking sqlite3 directly you could do python manage.py dbshell and then type the sqlite commands. If you are working with a legacy database you can generate Django models for that using the python … Read more

Simple Subquery with OuterRef

One of the problems with your example is that you cannot use queryset.count() as a subquery, because .count() tries to evaluate the queryset and return the count. So one may think that the right approach would be to use Count() instead. Maybe something like this: Post.objects.annotate( count=Count(Tag.objects.filter(post=OuterRef(‘pk’))) ) This won’t work for two reasons: The … Read more

Django – Rollback save with transaction atomic

Atomicity Documentation To summarize, @transaction.atomic will execute a transaction on the database if your view produces a response without errors. Because you’re catching the exception yourself, it appears to Django that your view executed just fine. If you catch the exception, you need to handle it yourself: Controlling Transactions If you need to produce a … Read more

How can I subtract or add 100 years to a datetime field in the database in Django?

I would use the relativedelta function of the dateutil.relativedelta package, which will give you are more accurate ‘n-years ago’ calculation: from dateutil.relativedelta import relativedelta import datetime years_ago = datetime.datetime.now() – relativedelta(years=5) Then simply update the date field as others have shown here.

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)