I am creating a django cursor in a views.py
def getDetails(request, name):
sql = 'select * from myTable where name=%s' % name
cursor = connections['default'].cursor()
cursor.execute(sql)
I don't explicitly close the cursor or use context manager (with keyword).
I want to know if the cursors are destroyed or they persist after each request response cycle in django. I am using django 1.4
Related
I have the functions that performs some CRUD operations with database like this:
def get_user_by_id(user_id):
db = get_db()
cursor = db.cursor(cursor_factory=extras.DictCursor)
cursor.execute(
'SELECT * FROM users WHERE id = %s',
(user_id, )
)
user = cursor.fetchone()
cursor.close()
return user
I want to test it with pytest, but don't know the right way to do it.
For example to get user data from database I should first create it and then call tested function. But should I call my create_user() function at setup and then call tested get_user_by_id()? Or it would be better to populate database with some test data and then use it? Should I test this kind of functions at all?
I have some queryset qs = MyModel.objects.filter(fieldname='fieldname') and a custom plpgsql function my_function(), that I can use in pg_shell like:
SELECT my_function('SELECT * FROM my_model');
How to do this with Django ORM? I tried to:
with connection.cursor() as cursor:
query, params = qs.query.sql_with_params()
query = f"SELECT my_function('{query}')"
cursor.execute(query, params)
But qs.query.sql_with_params() is not intended to return valid SQL.
Is something like this even possible with Django ORM?
First of all, if you want to call function/procedure do it like
from django.db import connections
connection = connections['default']
with connection.cursor() as cursor:
cursor.callproc('name_of_your_function', ('SELECT * FROM some_table WHERE whatever_you_want', ))
result = cursor.fetchone()
Next thing is about real sql query from django orm, not poor query that brings queryset.query or qs.query.sql_with_params especially in case you work with dates but the real one that will pass to psycopg
from .models import SomeModel
qs = SomeModel.objects.filter(create_at__gt='2021-04-20')
from django.db import connections
conn = connections['default']
from django.db.models.sql.compiler import SQLCompiler
compiler = SQLCompiler(qs.query, conn, using=qs.using)
sql, params = compiler.as_sql()
I have a Django project that utilizes multiple databases. https://docs.djangoproject.com/en/dev/topics/db/multi-db/
I perform a lot of raw queries like this:
cursor = connection.cursor()
cursor.execute("select * from my_table")
....
transaction.commit_unless_managed()
How can I specify which database to use?
Refer django docs on executing custom query directly. Specify database in your connection as given below:
from django.db import connections
cursor = connections['db_alias'].cursor()
cursor.execute("select * from my_table")
And then commit using
from django.db import transaction
transaction.commit_unless_managed(using='db_alias')
try this may be it should works.
from django.db import connections
cursor = connections[’my_db_name’].cursor()
# Your code here...
transaction.commit_unless_managed(using=’my_db_name’)
Is there any nothing wrong with this raw query?
Worker.objects.raw('Delete from customer_worker Where customer_ptr_id= %s', [customer.id])
Customer id returns a string, but it seems like nothing happen, the object is still there after the execution.
The object Worker is a child object from Customer, I want to remain the customer, but delete the Worker object.
Here are the Customer and Worker models:
class Customer(User):
slug=models.SlugField(unique=True)
description=models.TextField(null=True)
phone=models.IntegerField(null=True)
isWorker=models.BooleanField()
def save(self,*args,**kwargs):
self.slug=slugify(self.username)
super(Customer,self).save(*args, **kwargs)
def __unicode__(self):
return self.username
class Worker(Customer):
comment=models.ForeignKey(Comment, null=True)
keyword=models.ManyToManyField('job.JobGenre', null=True)
def __unicode__(self):
return self.username
You can delete your record(s) directly via connection.cursor() (docs):
from django.db import connection
cursor = connection.cursor()
cursor.execute('DELETE FROM costumer_worker WHERE costumer_ptr_id = %s', [costumer.id])
connection.commit()
But, the thing you're trying to do looks too simple to write SQL directly, use django ORM instead.
You may be missing comitting the transcation. Based on your settings, you may need to add :
transaction.commit_unless_managed() in django 1.4 ( not needed in django 1.5, since default settings are different)
use this line:
from django.db import connection, transaction
cursor = connection.cursor()
with transaction.commit_on_success():
cursor.execute('DELETE FROM costumer_worker WHERE costumer_ptr_id = %s', [costumer.id])
connection.commit()
Hello thanks for reading. I am doing a quick site in Django and I have a very simple update statement in raw SQL I am making to my Postgres database. Something in here is making trouble:
from django.http import HttpResponse
from django.db import connection, transaction
def rsvp_update(request, rsvp_id, status):
cursor = connection.cursor()
cursor.execute("UPDATE public.rsvp SET status=%s WHERE rsvp_id = %s", [status, rsvp_id])
transaction.commit()
return HttpResponse('okay')
I am getting an error that says "TransactionManagementError at [URL]
This code isn't under transaction management". Any ideas?
You need to use the commit_manually decorator for the code where you manage transactions manually.