在Model中可以
class City(models.Model):
CityID = models.IntegerField(unique=True, primary_key=True)
CityName = models.CharField(max_length=300, blank=True)
CityEnName = models.CharField(max_length=300, blank=True)
city_list = []
city_dict = {}
using = 'citydb' #使用指定的数据库
class Meta:
db_table = u'CityList'
@staticmethod
def getCityEnName(cityid):
if cityid == 0:
return u'All'
if cityid < 0:
return u'Unknown'
try:
cityenname = City.objects.using(City.using).values('CityEnName').filter(CityID=cityid) #得到一个QuerySet 如:[{'CityEnName': u'beijing'}]
cityenname = City.objects.using(City.using).get(CityID=cityid).CityEnName #得到指定的字段值
except ObjectDoesNotExist:
return 'Unknown'
return cityenname
class CityManager(models.Manager):
def getCityEnNameByID(self, cityid):
citylist = None
if cityid is not None:
citylist = super(CityManager, self).get_query_set() \
.values("cityenname") \
.filter(cityid=cid)
return citylist #得到[{'cityenname': u'beijing'}]的QuerySet
参照:
1. https://docs.djangoproject.com/en/dev/topics/db/models/
2. https://docs.djangoproject.com/en/dev/ref/models/querysets/
3. https://docs.djangoproject.com/en/dev/topics/db/queries/