当前位置: 首页>>代码示例>>Python>>正文


Python filters.run_model_query函数代码示例

本文整理汇总了Python中tracker.filters.run_model_query函数的典型用法代码示例。如果您正苦于以下问题:Python run_model_query函数的具体用法?Python run_model_query怎么用?Python run_model_query使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了run_model_query函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: donate

def donate(request, event):
    event = viewutil.get_event(event)
    if event.locked:
        raise Http404
    commentform, bidsform, prizesform = process_form(request, event)
    if not bidsform:  # redirect
        return commentform

    def bid_parent_info(bid):
        if bid != None:
            return {'name': bid.name, 'description': bid.description, 'parent': bid_parent_info(bid.parent)}
        else:
            return None

    def bid_info(bid):
        result = {
            'id': bid.id,
            'name': bid.name,
            'description': bid.description,
            'label': bid.full_label(not bid.allowuseroptions),
            'count': bid.count,
            'amount': bid.total,
            'goal': Decimal(bid.goal or '0.00'),
            'parent': bid_parent_info(bid.parent)
        }
        if bid.speedrun:
            result['runname'] = bid.speedrun.name
        if bid.suggestions.exists():
            result['suggested'] = list(
                map(lambda x: x.name, bid.suggestions.all()))
        if bid.allowuseroptions:
            result['custom'] = ['custom']
            result['label'] += ' (select and add a name next to "New Option Name")'
        return result

    bids = filters.run_model_query('bidtarget', {'state': 'OPENED', 'event': event.id}, user=request.user).distinct(
    ).select_related('parent').prefetch_related('suggestions')

    allPrizes = filters.run_model_query(
        'prize', {'feed': 'current', 'event': event.id})

    prizes = allPrizes.filter(ticketdraw=False)

    dumpArray = [bid_info(o) for o in bids]

    bidsJson = json.dumps(dumpArray, ensure_ascii=False,
                          cls=serializers.json.DjangoJSONEncoder)

    ticketPrizes = allPrizes.filter(ticketdraw=True)

    def prize_info(prize):
        result = {'id': prize.id, 'name': prize.name, 'description': prize.description,
                  'minimumbid': prize.minimumbid, 'maximumbid': prize.maximumbid, 'sumdonations': prize.sumdonations}
        return result

    dumpArray = [prize_info(o) for o in ticketPrizes.all()]
    ticketPrizesJson = json.dumps(
        dumpArray, ensure_ascii=False, cls=serializers.json.DjangoJSONEncoder)

    return views_common.tracker_response(request, "tracker/donate.html", {'event': event, 'bidsform': bidsform, 'prizesform': prizesform, 'commentform': commentform, 'hasBids': bids.count() > 0, 'bidsJson': bidsJson, 'hasTicketPrizes': ticketPrizes.count() > 0, 'ticketPrizesJson': ticketPrizesJson, 'prizes': prizes})
开发者ID:TipoftheHats,项目名称:donation-tracker,代码行数:60,代码来源:donateviews.py

示例2: user_index

def user_index(request):
    eventSet = {}
    
    for futureEvent in filters.run_model_query('event', {'feed': 'future'}):
        eventDict = eventSet.setdefault(futureEvent, {'event': futureEvent})
        eventDict['submission'] = futureEvent

    for prize in models.Prize.objects.filter(handler=request.user):
        eventDict = eventSet.setdefault(prize.event, {'event': prize.event})
        prizeList = eventDict.setdefault('prizes', [])
        prizeList.append(prize)

    donor = request.user.donor
    if donor != None:
        for prizeWin in models.PrizeWinner.objects.filter(Q(winner=donor)&(Q(pendingcount__gte=1)|Q(acceptcount__gte=1))):
            print(prizeWin)
            eventDict = eventSet.setdefault(prizeWin.prize.event, {'event': prizeWin.prize.event})
            prizeWinList = eventDict.setdefault('prizewins', [])
            prizeWinList.append(prizeWin)
        
    eventList = []
    
    for key,value in eventSet.iteritems():
        value['eventname'] = value['event'].name
        value['eventid'] = value['event'].id
        value.setdefault('submission', False)
        eventList.append(value)

    eventList.sort(key=lambda x: x['event'].date)

    return views_common.tracker_response(request, "tracker/user_index.html", {'eventList': eventList, })
开发者ID:DreadWingKnight,项目名称:donation-tracker,代码行数:31,代码来源:user.py

示例3: bidindex

def bidindex(request, event=None):
  event = viewutil.get_event(event)
  searchForm = BidSearchForm(request.GET)
  
  if not searchForm.is_valid():
    return HttpResponse('Invalid filter form', status=400)
    
  searchParams = {}
  searchParams.update(request.GET)
  searchParams.update(searchForm.cleaned_data)
  
  if event.id:
    searchParams['event'] = event.id
  else:
    return HttpResponseRedirect(reverse('tracker.views.bidindex', args=(Event.objects.latest().id,)))
    
  bids = filters.run_model_query('bid', searchParams, user=request.user)
  bids = bids.filter(parent=None)
  total = bids.aggregate(Sum('total'))['total__sum'] or Decimal('0.00')
  choiceTotal = bids.filter(goal=None).aggregate(Sum('total'))['total__sum'] or Decimal('0.00')
  challengeTotal = bids.exclude(goal=None).aggregate(Sum('total'))['total__sum'] or Decimal('0.00')
  bids = viewutil.get_tree_queryset_descendants(Bid, bids, include_self=True).prefetch_related('options')
  bids = bids.filter(parent=None)
  
  if event.id:
    bidNameSpan = 2
  else:
    bidNameSpan = 1
    
  return views_common.tracker_response(request, 'tracker/bidindex.html', { 'searchForm': searchForm, 'bids': bids, 'total': total, 'event': event, 'bidNameSpan' : bidNameSpan, 'choiceTotal': choiceTotal, 'challengeTotal': challengeTotal })
开发者ID:uraniumanchor,项目名称:sda-donation-tracker-2-read-only,代码行数:30,代码来源:public.py

示例4: post_donation_to_postbacks

def post_donation_to_postbacks(donation):
    event_donations = filters.run_model_query('donation',
                                              {'event': donation.event.id})
    total = event_donations.aggregate(amount=Sum('amount'))['amount']

    data = {
        'id': donation.id,
        'timereceived': str(donation.timereceived),
        'comment': donation.comment,
        'amount': donation.amount,
        'donor__visibility': donation.donor.visibility,
        'donor__visiblename': donation.donor.visible_name(),
        'new_total': total,
        'domain': donation.domain
    }

    # XXX: django/urllib2 throws UnicodeDecideError when payloads contain
    # unicode codepoints:
    #   UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 292: ordinal not in range(128)
    try:
        data_json = json.dumps(
            data, ensure_ascii=False, cls=serializers.json.DjangoJSONEncoder).encode('utf-8')

        postbacks = models.PostbackURL.objects.filter(event=donation.event)
        for postback in postbacks:
            opener = urllib2.build_opener()
            req = urllib2.Request(postback.url, data_json,
                                  headers={'Content-Type': 'application/json; charset=utf-8'})
            response = opener.open(req, timeout=5)
    except Exception as e:
        viewutil.tracker_log(
            'postback_url', traceback.format_exc(), event=donation.event)
开发者ID:TipoftheHats,项目名称:donation-tracker,代码行数:32,代码来源:eventutil.py

示例5: user_index

def user_index(request):
    eventSet = {}

    for futureEvent in filters.run_model_query('event', {'feed': 'future'}):
        if not futureEvent.locked:
            eventDict = eventSet.setdefault(
                futureEvent, {'event': futureEvent})
            eventDict['submission'] = futureEvent

    for prize in models.Prize.objects.filter(handler=request.user):
        eventDict = eventSet.setdefault(prize.event, {'event': prize.event})
        prizeList = eventDict.setdefault('prizes', [])
        prizeList.append(prize)

    eventList = []

    for key, value in eventSet.iteritems():
        value['eventname'] = value['event'].name
        value['eventid'] = value['event'].id
        value.setdefault('submission', False)
        eventList.append(value)

    eventList.sort(key=lambda x: x['event'].date)

    return views_common.tracker_response(request, "tracker/user_index.html", {'eventList': eventList, })
开发者ID:TipoftheHats,项目名称:donation-tracker,代码行数:25,代码来源:user.py

示例6: get_queryset

 def get_queryset(self, request):
   event = viewutil.get_selected_event(request)
   params = {}
   if not request.user.has_perm('tracker.can_edit_locked_events'):
     params['locked'] = False
   if event:
     params['event'] = event.id
   return filters.run_model_query('log', params, user=request.user, mode='admin')
开发者ID:bsstephan,项目名称:donation-tracker,代码行数:8,代码来源:admin.py

示例7: get_query

 def get_query(self,q,request):
   params = {'q': q}
   event = viewutil.get_selected_event(request)
   if event and self.useEvent:
     params['event'] = event.id
   model = self.model
   if hasattr(self, 'modelName'):
     model = self.modelName
   if self.useLock and not request.user.has_perm('tracker.can_edit_locked_events'):
     params['locked'] = False
   return filters.run_model_query(model, params, user=request.user, mode='admin')
开发者ID:GamesDoneQuick,项目名称:donation-tracker,代码行数:11,代码来源:lookups.py

示例8: index

def index(request,event=None):
  event = viewutil.get_event(event)
  eventParams = {}
  if event.id:
    eventParams['event'] = event.id
  agg = filters.run_model_query('donation', eventParams, user=request.user, mode='user').aggregate(amount=Sum('amount'), count=Count('amount'), max=Max('amount'), avg=Avg('amount'))
  agg['target'] = event.targetamount
  count = {
    'runs' : filters.run_model_query('run', eventParams, user=request.user).count(),
    'prizes' : filters.run_model_query('prize', eventParams, user=request.user).count(),
    'bids' : filters.run_model_query('bid', eventParams, user=request.user).count(),
    'donors' : filters.run_model_query('donorcache', eventParams, user=request.user).values('donor').distinct().count(),
  }

  if 'json' in request.GET:
    return HttpResponse(json.dumps({'count':count,'agg':agg},ensure_ascii=False),content_type='application/json;charset=utf-8')
  elif 'jsonp' in request.GET:
    callback = request.GET['jsonp']
    return HttpResponse('%s(%s);' % (callback, json.dumps({'count':count,'agg':agg},ensure_ascii=False)), content_type='text/javascript;charset=utf-8')
  return tracker_response(request, 'tracker/index.html', { 'agg' : agg, 'count' : count, 'event': event })
开发者ID:quinox,项目名称:sda-donation-tracker-2,代码行数:20,代码来源:views.py

示例9: index

def index(request, event=None):
    event = viewutil.get_event(event)
    eventParams = {}

    if event.id:
        eventParams['event'] = event.id

    agg = filters.run_model_query('donation', eventParams).aggregate(amount=Sum(
        'amount'), count=Count('amount'), max=Max('amount'), avg=Avg('amount'))
    agg['target'] = event.targetamount
    count = {
        'runs': filters.run_model_query('run', eventParams).count(),
        'prizes': filters.run_model_query('prize', eventParams).count(),
        'bids': filters.run_model_query('bid', eventParams).count(),
        'donors': filters.run_model_query('donorcache', eventParams).values('donor').distinct().count(),
    }

    if 'json' in request.GET:
        return HttpResponse(json.dumps({'count': count, 'agg': agg}, ensure_ascii=False, cls=serializers.json.DjangoJSONEncoder), content_type='application/json;charset=utf-8')

    return views_common.tracker_response(request, 'tracker/index.html', {'agg': agg, 'count': count, 'event': event})
开发者ID:TipoftheHats,项目名称:donation-tracker,代码行数:21,代码来源:public.py

示例10: search

def search(request):
    authorizedUser = request.user.has_perm('tracker.can_search')
    #  return HttpResponse('Access denied',status=403,content_type='text/plain;charset=utf-8')
    try:
        searchParams = viewutil.request_params(request)
        searchtype = searchParams['type']
        qs = filters.run_model_query(searchtype, searchParams, user=request.user, mode='admin' if authorizedUser else 'user')
        if searchtype in related:
            qs = qs.select_related(*related[searchtype])
        if searchtype in defer:
            qs = qs.defer(*defer[searchtype])
        qs = qs.annotate(**viewutil.ModelAnnotations.get(searchtype,{}))
        if qs.count() > 1000:
            qs = qs[:1000]
        jsonData = json.loads(serializers.serialize('json', qs, ensure_ascii=False))
        objs = dict(map(lambda o: (o.id,o), qs))
        for o in jsonData:
            baseObj = objs[int(o['pk'])]
            if isinstance(baseObj, Donor):
                o['fields']['public'] = baseObj.visible_name()
            else:
                o['fields']['public'] = unicode(baseObj)
            for a in viewutil.ModelAnnotations.get(searchtype,{}):
                o['fields'][a] = unicode(getattr(objs[int(o['pk'])],a))
            for r in related.get(searchtype,[]):
                ro = objs[int(o['pk'])]
                for f in r.split('__'):
                    if not ro: break
                    ro = getattr(ro,f)
                if not ro: continue
                relatedData = json.loads(serializers.serialize('json', [ro], ensure_ascii=False))[0]
                for f in ro.__dict__:
                    if f[0] == '_' or f.endswith('id') or f in defer.get(searchtype,[]): continue
                    v = relatedData["fields"][f]
                    o['fields'][r + '__' + f] = relatedData["fields"][f]
                if isinstance(ro, Donor):
                    o['fields'][r + '__public'] = ro.visible_name()
                else:
                    o['fields'][r + '__public'] = unicode(ro)
            if not authorizedUser:
                donor_privacy_filter(searchtype, o['fields'])
                donation_privacy_filter(searchtype, o['fields'])
                prize_privacy_filter(searchtype, o['fields'])
            clean_fields = getattr(Filters, searchtype, None)
            if clean_fields:
                clean_fields(request.user, o['fields'])
        resp = HttpResponse(json.dumps(jsonData,ensure_ascii=False),content_type='application/json;charset=utf-8')
        if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
            return HttpResponse(json.dumps(connection.queries, ensure_ascii=False, indent=1),content_type='application/json;charset=utf-8')
        return resp
    except KeyError, e:
        return HttpResponse(json.dumps({'error': 'Key Error, malformed search parameters'}, ensure_ascii=False), status=400, content_type='application/json;charset=utf-8')
开发者ID:GamesDoneQuick,项目名称:donation-tracker,代码行数:52,代码来源:api.py

示例11: runindex

def runindex(request,event=None):
  event = viewutil.get_event(event)
  searchForm = RunSearchForm(request.GET)
  if not searchForm.is_valid():
    return HttpResponse('Invalid Search Data', status=400)
  searchParams = {}
  searchParams.update(request.GET)
  searchParams.update(searchForm.cleaned_data)
  if event.id:
    searchParams['event'] = event.id
  runs = filters.run_model_query('run', searchParams, user=request.user)
  runs = runs.select_related('runners').annotate(hasbids=Sum('bids'))
  return tracker_response(request, 'tracker/runindex.html', { 'searchForm': searchForm, 'runs' : runs, 'event': event })
开发者ID:quinox,项目名称:sda-donation-tracker-2,代码行数:13,代码来源:views.py

示例12: run

def run(request,id):
  try:
    run = SpeedRun.objects.get(pk=id)
    runners = run.runners.all()
    event = run.event
    bids = filters.run_model_query('bid', {'run': id}, user=request.user)
    bids = viewutil.get_tree_queryset_descendants(Bid, bids, include_self=True).select_related('speedrun','event', 'parent').prefetch_related('options')
    topLevelBids = filter(lambda bid: bid.parent == None, bids)
    bids = topLevelBids

    return tracker_response(request, 'tracker/run.html', { 'event': event, 'run' : run, 'runners': runners, 'bids' : topLevelBids })
  except SpeedRun.DoesNotExist:
    return tracker_response(request, template='tracker/badobject.html', status=404)
开发者ID:quinox,项目名称:sda-donation-tracker-2,代码行数:13,代码来源:views.py

示例13: prizeindex

def prizeindex(request,event=None):
  event = viewutil.get_event(event)
  searchForm = PrizeSearchForm(request.GET)
  if not searchForm.is_valid():
    return HttpResponse('Invalid Search Data', status=400)
  searchParams = {}
  searchParams.update(request.GET)
  searchParams.update(searchForm.cleaned_data)
  if event.id:
    searchParams['event'] = event.id
  prizes = filters.run_model_query('prize', searchParams, user=request.user)
  prizes = prizes.select_related('startrun','endrun','category').prefetch_related('prizewinner_set')
  return tracker_response(request, 'tracker/prizeindex.html', { 'searchForm': searchForm, 'prizes' : prizes, 'event': event })
开发者ID:quinox,项目名称:sda-donation-tracker-2,代码行数:13,代码来源:views.py

示例14: index

def index(request, event=None):
    event = viewutil.get_event(event)
    eventParams = {}

    if event.id:
        eventParams["event"] = event.id

    agg = filters.run_model_query("donation", eventParams, user=request.user, mode="user").aggregate(
        amount=Sum("amount"), count=Count("amount"), max=Max("amount"), avg=Avg("amount")
    )
    agg["target"] = event.targetamount
    count = {
        "runs": filters.run_model_query("run", eventParams, user=request.user).count(),
        "prizes": filters.run_model_query("prize", eventParams, user=request.user).count(),
        "bids": filters.run_model_query("bid", eventParams, user=request.user).count(),
        "donors": filters.run_model_query("donorcache", eventParams, user=request.user)
        .values("donor")
        .distinct()
        .count(),
    }

    if "json" in request.GET:
        return HttpResponse(
            json.dumps({"count": count, "agg": agg}, ensure_ascii=False, cls=serializers.json.DjangoJSONEncoder),
            content_type="application/json;charset=utf-8",
        )
    elif "jsonp" in request.GET:
        callback = request.GET["jsonp"]
        return HttpResponse(
            "%s(%s);"
            % (
                callback,
                json.dumps({"count": count, "agg": agg}, ensure_ascii=False, cls=serializers.json.DjangoJSONEncoder),
            ),
            content_type="text/javascript;charset=utf-8",
        )

    return views_common.tracker_response(request, "tracker/index.html", {"agg": agg, "count": count, "event": event})
开发者ID:GamesDoneQuick,项目名称:donation-tracker,代码行数:38,代码来源:public.py

示例15: get_donation_prize_info

def get_donation_prize_info(donation):
  """ Attempts to find a list of all prizes this donation gives the donor eligibility for.
    Does _not_ attempt to relate this information to any _past_ eligibility.
    Returns the set as a list of {'prize','amount'} dictionaries. """
  prizeList = []
  for ticket in donation.tickets.all():
    contribAmount = get_donation_prize_contribution(ticket.prize, donation, ticket.amount)
    if contribAmount != None:
      prizeList.append({'prize': ticket.prize, 'amount': contribAmount})
  for timeprize in filters.run_model_query( 'prize', params={ 'feed': 'current', 'ticketdraw': False, 'offset': donation.timereceived, 'noslice': True } ):
    contribAmount = get_donation_prize_contribution(timeprize, donation)
    if contribAmount != None:
      prizeList.append({'prize': timeprize, 'amount': contribAmount})
  return prizeList
开发者ID:DreadWingKnight,项目名称:donation-tracker,代码行数:14,代码来源:viewutil.py


注:本文中的tracker.filters.run_model_query函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。