def raw_data(self):
"""Return data suitable for use in payment and billing forms"""
data = model_to_dict(self)
data['card_code'] = getattr(self, 'card_code')
return data
python类model_to_dict()的实例源码
def model_to_dict(instance, **kwargs):
if kwargs.pop('all'):
kwargs['fields'] = [field.name for field in instance._meta.fields]
return model_to_dict_django(instance, **kwargs)
def profile(request):
current_user_id = request.user.id
user_histories = UserHistory.objects.all().filter(user_id=current_user_id)
context = {"skipped_grammars": [],
"completed_grammars": [],
"percentile": 0,
"user_info": {}}
available_score = 0
earned_score = 0
# get data for each grammar that the user has completed
for user_history in user_histories:
grammar = Grammar.objects.get(pk=user_history.grammar_id)
grammar_dict = model_to_dict(grammar, fields=["gid","prods","nonTerminals"])
stats_dict = model_to_dict(user_history, fields=["complete", "score", "updateTime"])
stats_dict.update(grammar_dict)
nQuestions = (2 * len(stats_dict['nonTerminals']) + 2)
available_score += nQuestions
if stats_dict["complete"]:
stats_dict["grammar_avg"] = get_grammar_avg(user_history.grammar_id)
stats_dict["total_score"] = nQuestions
context["completed_grammars"].append(stats_dict)
earned_score += stats_dict["score"]
else:
context["skipped_grammars"].append(stats_dict)
#sort grammarhistory based on time
context["completed_grammars"] = sorted(context["completed_grammars"], key=lambda k: k['updateTime'])
context["skipped_grammars"] = sorted(context["skipped_grammars"], key=lambda k: k['updateTime'])
# get user information
user_info = model_to_dict(User.objects.get(pk=current_user_id), ["first_name", "last_name", "data_joined", "email", "last_login"])
context["percentile"] = round(get_user_performance(current_user_id),2)
context["user_info"] = user_info
#pack up infos for the pie charts
chart_stats = {"correct": earned_score, "wrong": available_score-earned_score}
chart_stats.update(get_complete_rate(current_user_id))
context["chart_stats"] = json.dumps(chart_stats)
return render(request, 'LL1_Academy/profile.html', context)
def shipping_address(self, address):
address_data = model_to_dict(address)
address_data['country'] = smart_text(address_data['country'])
self.storage['shipping_address'] = address_data
self.modified = True
self._shipping_address = address
def billing_address(self, address):
address_data = model_to_dict(address)
address_data['country'] = smart_text(address_data['country'])
self.storage['billing_address'] = address_data
self.modified = True
def as_data(self, address):
"""Return the address as a dict suitable for passing as kwargs.
Result does not contain the primary key or an associated user.
"""
data = model_to_dict(address, exclude=['id', 'user'])
if isinstance(data['country'], Country):
data['country'] = data['country'].code
return data
def field_values(self):
"""Returns the user's field-values (can be encoded as e.g. JSON)."""
return model_to_dict(self, exclude=['password'])
def as_dict(self):
ret_dict = model_to_dict(self)
ret_dict['requests'] = [r.as_dict for r in self.requests.all()]
return ret_dict
def as_dict(self):
ret_dict = model_to_dict(self)
ret_dict['target'] = self.target.as_dict
ret_dict['molecules'] = [m.as_dict for m in self.molecules.all()]
ret_dict['location'] = self.location.as_dict
ret_dict['constraints'] = self.constraints.as_dict
ret_dict['windows'] = [w.as_dict for w in self.windows.all()]
return ret_dict
def as_dict(self):
return model_to_dict(self)
def as_dict(self):
return model_to_dict(self)
def as_dict(self):
return model_to_dict(self)
def as_dict(self):
return model_to_dict(self)
def get_all():
""" Get all threshold
"""
return [model_to_dict(thres) for thres in ReportThreshold.objects.all()]
def show(threshold_id):
""" Get infos for specified threshold
"""
try:
threshold = ReportThreshold.objects.get(id=threshold_id)
return model_to_dict(threshold)
except ValueError:
raise BadRequest('Not a valid threshold id')
except ObjectDoesNotExist:
raise NotFound('Threshold not found')
def create(body):
""" Create threshold
"""
try:
category = Category.objects.get(name=body['category'])
if ReportThreshold.objects.filter(category=category).exists():
raise BadRequest('Threshold already exists for this category')
body['category'] = category
threshold, created = ReportThreshold.objects.get_or_create(**body)
except (KeyError, FieldError, IntegrityError, ObjectDoesNotExist):
raise BadRequest('Missing or invalid fields in body')
if not created:
raise BadRequest('Threshold already exists')
return model_to_dict(threshold)
def update(threshold_id, body):
""" Update threshold
"""
try:
threshold = ReportThreshold.objects.get(id=threshold_id)
except (ObjectDoesNotExist, ValueError):
raise NotFound('Threshold not found')
try:
body = {k: v for k, v in body.iteritems() if k in ['threshold', 'interval']}
ReportThreshold.objects.filter(pk=threshold.pk).update(**body)
threshold = ReportThreshold.objects.get(pk=threshold.pk)
except (KeyError, FieldError, IntegrityError):
raise BadRequest('Missing or invalid fields in body')
return model_to_dict(threshold)
def index(**kwargs):
""" Get all tags
"""
where = [Q()]
if 'tagType' in kwargs:
where.append(Q(tagType__iexact=kwargs['tagType']))
where = reduce(operator.and_, where)
tags = Tag.objects.filter(where)
return [model_to_dict(tag) for tag in tags]
def get_prefetch_preset(user, ticket_id, preset_id, lang=None):
"""
Prefetch preset with ticket infos
"""
action = params = None
try:
ticket = Ticket.objects.get(id=ticket_id)
preset = TicketWorkflowPreset.objects.get(id=preset_id, roles=user.operator.role)
if preset.config:
action = model_to_dict(preset.config.action)
if preset.config.params:
params = {param.codename: param.value for param in preset.config.params.all()}
preset = model_to_dict(preset)
except (ObjectDoesNotExist, ValueError):
raise NotFound('Ticket or preset not found')
preset['templates'] = []
templates_codename = MailTemplate.objects.filter(
ticketworkflowpreset=preset['id']
).values_list(
'codename',
flat=True
)
templates_codename = list(set(templates_codename))
for codename in templates_codename:
template = MailTemplate.objects.get(codename=codename)
resp = TemplatesController.get_prefetch_template(ticket.id, template.id, lang=lang)
preset['templates'].append(resp)
preset['action'] = action
if action and params:
preset['action']['params'] = params
return preset
def show(user, preset_id):
"""
Get given preset
"""
try:
preset = TicketWorkflowPreset.objects.get(id=preset_id, roles=user.operator.role)
except (IndexError, ObjectDoesNotExist, ValueError, TypeError):
raise NotFound('Preset not found')
action = params = None
if preset.config:
action = model_to_dict(preset.config.action)
if preset.config.params:
params = {param.codename: param.value for param in preset.config.params.all()}
preset = model_to_dict(preset)
preset['templates'] = MailTemplate.objects.filter(ticketworkflowpreset=preset['id'])
preset['templates'] = [model_to_dict(m) for m in preset['templates']]
preset['action'] = action
if action and params:
preset['action']['params'] = params
preset['roles'] = list(TicketWorkflowPreset.objects.get(
id=preset['id']
).roles.all().values_list(
'codename',
flat=True
).distinct())
return preset