I have an class definition:
class ScoreDetail(Document): location = StringField(help_text = "province") school = StringField(help_text = "school") spec = StringField(help_text = "major") bz = IntField(help_text = "1: Bachelor, 2: Academy, 0: exception") wl = IntField(help_text = "1: w, 2: l, 0: exception") batch = StringField(help_text = "batch") score = IntField(help_text = "score") average_score = FloatField(help_text = "average score") average_score_rank = FloatField(help_text = "rank of average score") low_score = IntField(help_text = "the lowest score") low_score_rank = IntField(help_text = "rank of the lowest score") high_score = IntField(help_text = "highest score") high_score_rank = IntField(help_text = "rank of the highest score") score_number = IntField(help_text = "people in this score") spec_number = IntField(help_text = "people in the major") rank = IntField(help_text = "rank") year = IntField('year')
Now I have a dict named item
, like this:
{ "school": u"Peking University", "average_score": u"255", "low_score_rank": u"195466", "wl": u"w", "batch": u"4", "score_number": u"1", "average_score_rank": u"178199", "low_score": u"150", "high_score": u"464", "score": u"150", "spec_number": u"62", "rank": u"195466", "year": u"14", "high_score_rank": u"60631", "spec": u"E-commerce", "bz": u"z", "location": u"US" }
I want construct a ScoreDetail
object from this dict, so I do this:
wl_map = {'w': 1, 'l': 2} bz_map = {'b': 1, 'z': 2} item['wl'] = wl_map[item['wl']] item['year'] = '20' + item['year'] item['bz'] = bz_map[item['bz']] s = ScoreDetail( school=item['school'], average_score=item['average_score'], low_score_rank=item['low_score_rank'], wl=item['wl'], batch=item['batch'], score_number=item['score_number'], average_score_rank=item['average_score_rank'], low_score=item['low_score'], high_score=item['high_score'], score=item['score'], spec_number=item['spec_number'], rank=item['rank'], year=item['year'], high_score_rank=item['high_score_rank'], spec=item['spec'], bz=item['bz'], location=item['location'] )
Now I want to know these two things:
- Can I simplify this code?
- As you can see, this is a
mongoengine schema
. It inheritsDocument
, so it can make'1'
toint
,'150'
tofloat
as default, but if I were not to use MongoEngine, this is just a common class. How can I make some type conversion as default?