django transform queryset to dict

model_to_dict方法

1
2
from django.forms.models import model_to_dict
model_to_dict(instance)

参考链接

toDict方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Category(models.Model):
autoid = models.AutoField(primary_key=True)
email=models.CharField(max_length=150,blank=False)
comtype=models.CharField(max_length=20,blank=False)
catname=models.CharField(max_length=150,blank=False)
def __unicode__(self):
return '%s' % (self.catname)
def toJSON(self):
import json
return json.dumps(dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]]))
def toDict(self):
return dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]])

可读性更强的版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def toJSON(self):
fields = []
for field in self._meta.fields:
fields.append(field.name)
d = {}
for attr in fields:
d[attr] = getattr(self, attr)
import json
return json.dumps(d)
def toDict(self):
fields = []
for field in self._meta.fields:
fields.append(field.name)
d = {}
for attr in fields:
d[attr] = getattr(self, attr)
return d

参考链接

django pagination demo

1. a demo for using pagination

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def listing(request):
contact_list = Contacts.objects.all()
paginator = Paginator(contact_list, 25) # Show 25 contacts per page
page = request.GET.get('page')
try:
contacts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
contacts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
contacts = paginator.page(paginator.num_pages)
return render_to_response('list.html', {"contacts": contacts})

django_182

2. get objects length

1
2
cnt = contact_list.count()
cnt = Contacts.objects.all().count()

django multi database

1. 在setting.py中定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
DATABASES = {
'default': {
'NAME': 'app_data',
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'USER': 'postgres_user',
'PASSWORD': 's3krit'
},
'users': {
'NAME': 'user_data',
'ENGINE': 'django.db.backends.mysql',
'USER': 'mysql_user',
'PASSWORD': 'priv4te'
}
}

2. 使用using手动选择一个数据库

1
2
>>> u = User.objects.using('legacy_users').get(username='fred')
>>> u.delete() # will delete from the `legacy_users` database

django_182