python类model_to_dict()的实例源码

profile.py 文件源码 项目:sarafu 作者: pesaply 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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
admin.py 文件源码 项目:ecs_sclm 作者: meaningful 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
userProfile.py 文件源码 项目:LL1-Academy 作者: H-Huang 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
core.py 文件源码 项目:planet-b-saleor 作者: planet-b 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
core.py 文件源码 项目:planet-b-saleor 作者: planet-b 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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
models.py 文件源码 项目:planet-b-saleor 作者: planet-b 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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
models.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def field_values(self):
        """Returns the user's field-values (can be encoded as e.g. JSON)."""
        return model_to_dict(self, exclude=['password'])
models.py 文件源码 项目:valhalla 作者: LCOGT 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
models.py 文件源码 项目:valhalla 作者: LCOGT 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
models.py 文件源码 项目:valhalla 作者: LCOGT 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def as_dict(self):
        return model_to_dict(self)
models.py 文件源码 项目:valhalla 作者: LCOGT 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def as_dict(self):
        return model_to_dict(self)
models.py 文件源码 项目:valhalla 作者: LCOGT 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def as_dict(self):
        return model_to_dict(self)
models.py 文件源码 项目:valhalla 作者: LCOGT 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def as_dict(self):
        return model_to_dict(self)
ThresholdController.py 文件源码 项目:cerberus-core 作者: ovh 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get_all():
    """ Get all threshold
    """
    return [model_to_dict(thres) for thres in ReportThreshold.objects.all()]
ThresholdController.py 文件源码 项目:cerberus-core 作者: ovh 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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')
ThresholdController.py 文件源码 项目:cerberus-core 作者: ovh 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
ThresholdController.py 文件源码 项目:cerberus-core 作者: ovh 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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)
TagsController.py 文件源码 项目:cerberus-core 作者: ovh 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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]
PresetsController.py 文件源码 项目:cerberus-core 作者: ovh 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
PresetsController.py 文件源码 项目:cerberus-core 作者: ovh 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号