-
Notifications
You must be signed in to change notification settings - Fork 183
/
Copy pathmodels.py
59 lines (47 loc) · 1.62 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from django.db import models
from collections import namedtuple
from django.db import connection
# Create your models here.
class Music(models.Model):
song = models.TextField()
singer = models.TextField()
last_modify_date = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = "music"
app_label = "music"
def fun_raw_sql_query(**kwargs):
song = kwargs.get('song')
if song:
result = Music.objects.raw('SELECT * FROM music WHERE song = %s', [song])
else:
result = Music.objects.raw('SELECT * FROM music')
return result
def namedtuplefetchall(cursor):
# Return all rows from a cursor as a namedtuple
desc = cursor.description
nt_result = namedtuple('Result', [col[0] for col in desc])
return [nt_result(*row) for row in cursor.fetchall()]
def fun_sql_cursor_update(**kwargs):
song = kwargs.get('song')
pk = kwargs.get('pk')
'''
Note that if you want to include literal percent signs in the query,
you have to double them in the case you are passing parameters:
'''
with connection.cursor() as cursor:
cursor.execute("UPDATE music SET song = %s WHERE id = %s", [song, pk])
cursor.execute("SELECT * FROM music WHERE id = %s", [pk])
# result = cursor.fetchone()
result = namedtuplefetchall(cursor)
result = [
{
'id': r.id,
'song': r.song,
'singer': r.singer,
'last_modify_date': r.last_modify_date,
'created': r.created,
}
for r in result
]
return result