custom manager (table level)

  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
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
class PollManager(models.Manager):
def with_counts(self):
from django.db import connection
cursor = connection.cursor()
cursor.execute("""
SELECT p.id, p.question, p.poll_date, COUNT(*)
FROM polls_opinionpoll p, polls_response r
WHERE p.id = r.poll_id
GROUP BY 1, 2, 3
ORDER BY 3 DESC""")
result_list = []
for row in cursor.fetchall():
p = self.model(id=row[0], question=row[1], poll_date=row[2])
p.num_responses = row[3]
result_list.append(p)
return result_list
class OpinionPoll(models.Model):
question = models.CharField(max_length=200)
poll_date = models.DateField()
objects = PollManager()
class Response(models.Model):
poll = models.ForeignKey(Poll)
person_name = models.CharField(max_length=50)
response = models.TextField()
################################################
class Counter(models.Manager):
def something(self):
from django.db import connection
cursor = connection.cursor()
cursor.execute("""
SELECT * , COUNT( * )
FROM profile_sample
GROUP BY name
""")
results = []
for i in cursor.fetchall():
p = Sample()
p.id=i[0]
p.name=i[1]
p.coun_t = i[2]
results.append(p)
return results
class Sample(models.Model):
objects = Counter()
name = models.CharField(max_length=30)
##################################################
class Counter(models.Manager):
def something(self):
from django.db import connection
cursor = connection.cursor()
cursor.execute("""
SELECT * , COUNT( * )
FROM profile_sample
GROUP BY name
""")
results = []
for i in cursor.fetchall():
p = self.model(id=i[0],name=i[1])
p.coun_t = i[2]
results.append(p)
return results
class Sample(models.Model):
objects = Counter()
name = models.CharField(max_length=30)
################################################
#View
@render_to('test.html')
def test(request):
lam = Sample.objects.something()
return {'lam':lam}
###############################################
#template
{% for i in lam %}
{{ i.name }} {{ i.coun_t }}
{% endfor %}