Here are the examples of the python api django.db.models.Max taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
161 Examples
3
Example 1
Project: open-context-py Source File: math.py
def get_numeric_range(self, predicate_uuids, children_ok=True):
if not isinstance(predicate_uuids, list):
predicate_uuids = [str(predicate_uuids)]
sum_ass = Assertion.objects\
.filter(predicate_uuid__in=predicate_uuids)\
.aggregate(Min('data_num'),
Max('data_num'),
Count('hash_id'),
Avg('data_num'))
output = {}
output['avg'] = sum_ass['data_num__avg']
output['min'] = sum_ass['data_num__min']
output['max'] = sum_ass['data_num__max']
output['count'] = sum_ass['hash_id__count']
if output['count'] == 0 and children_ok:
output = self.get_numeric_range_from_children(predicate_uuids)
return output
3
Example 2
def get_queryset(self):
"""
Build a queryset of items with published entries and annotated
with the number of entries and the latest modification date.
"""
return self.model.published.annotate(
count_entries_published=Count('entries')).annotate(
last_update=Max('entries__last_update')).order_by(
'-count_entries_published', '-last_update', '-pk')
3
Example 3
def get_for_object(self, obj, **kwargs):
"""
Returns tags for an object, also returns the relevance score from
the supertaggingitem table.
"""
ctype = ContentType.objects.get_for_model(obj)
extra_args = {}
if 'field' in kwargs:
extra_args['supertaggeditem__field'] = kwargs['field']
order_by = kwargs.get('order_by', '-relevance')
return self.filter(
supertaggeditem__content_type__pk=ctype.pk,
supertaggeditem__object_id=obj.pk,
**extra_args).annotate(
relevance=models.Max('supertaggeditem__relevance')
).order_by(order_by)
3
Example 4
Project: django-popularity Source File: models.py
def select_relviews(self, relative_to=None):
""" Adds 'relview', a normalized viewcount, to the QuerySet.
The normalization occcurs relative to the maximum number of views
in the current QuerySet, unless specified in 'relative_to'.
The relative number of views should always in the range [0, 1]. """
assert self._DATABASE_ENGINE in COMPATIBLE_DATABASES, 'Database engine %s is not compatible with this functionality.'
if not relative_to:
relative_to = self
assert relative_to.__class__ == self.__class__, \
'relative_to should be of type %s but is of type %s' % (self.__class__, relative_to.__class__)
maxviews = relative_to.aggregate(models.Max('views'))['views__max']
SQL_RELVIEWS = self._SQL_RELVIEWS % {'maxviews' : maxviews}
return self._add_extra('relviews', SQL_RELVIEWS)
3
Example 5
def is_active(self):
max_date = self.source.points.aggregate(avg=Max('date'))['avg']
now = datetime.datetime.utcnow().replace(tzinfo=utc)
logger.debug("Max Date %s", max_date)
logger.debug("Now %s", now)
if max_date and now - max_date > datetime.timedelta(minutes=60):
return False
return True
3
Example 6
Project: pootle Source File: directory_data.py
@property
def max_unit_revision(self):
try:
return self.context.translationproject.data_tool.max_unit_revision
except TranslationProject.DoesNotExist:
return self.all_stat_data.aggregate(rev=Max("max_unit_revision"))["rev"]
3
Example 7
def get_deleted(self, model, model_db=None):
return self.get_for_model(model, model_db=model_db).filter(
pk__in=_safe_subquery(
"exclude",
self.get_for_model(model, model_db=model_db),
"object_id",
model._default_manager.using(model_db),
model._meta.pk.name,
).values_list("object_id").annotate(
latest_pk=models.Max("pk")
).order_by().values_list("latest_pk", flat=True),
)
3
Example 8
def save(self, **kwargs):
if self.position is None:
lastpos = SubmissionComponent.objects.filter(activity=self.activity) \
.aggregate(Max('position'))['position__max']
if lastpos is None:
lastpos = 0
self.position = lastpos+1
super(SubmissionComponent, self).save(**kwargs)
3
Example 9
def index_range(self, zoom):
"""
Compute the index range for this rasterlayer at a given zoom leve.
"""
return self.rastertile_set.filter(tilez=zoom).aggregate(
Min('tilex'), Max('tilex'), Min('tiley'), Max('tiley')
)
3
Example 10
Project: django-page-cms Source File: managers.py
def get_page_ids_by_slug(self, slug):
"""Return all page's id matching the given slug.
This function also returns pages that have an old slug
that match.
:param slug: the wanted slug.
"""
ids = self.filter(type='slug', body=slug).values('page_id').annotate(
max_creation_date=Max('creation_date')
)
return [content['page_id'] for content in ids]
3
Example 11
def get_context_data(self, **kwargs):
context = super(OrganizationUsers, self).get_context_data(**kwargs)
context['title'] = _('%s Members') % self.object.name
context['users'] = ranker(chain(*[
i.select_related('user__username').defer('about') for i in (
self.object.members.filter(submission__points__gt=0).order_by('-points')
.annotate(problems=Count('submission__problem', distinct=True)),
self.object.members.annotate(problems=Max('submission__points')).filter(problems=0),
self.object.members.annotate(problems=Count('submission__problem', distinct=True)).filter(problems=0),
)
]))
context['partial'] = True
context['is_admin'] = self.can_edit_organization()
context['kick_url'] = reverse('organization_user_kick', args=[self.object.key])
return context
3
Example 12
def get_next_position(self):
query = self.seriespage_set.all().aggregate(models.Max('position'))
max_position = query['position__max']
if max_position:
return max_position + 1
else:
return 1
3
Example 13
Project: read_FEC Source File: mark_superceded_body_rows.py
def summarize_f6(new_filing):
filing_skeda = SkedA.objects.filter(filing_number=new_filing.filing_number)
results = filing_skeda.aggregate(tot_raised=Sum('contribution_amount'), start_date=Min('contribution_date_formatted'), end_date=Max('contribution_date_formatted'))
if results:
new_filing.tot_raised = results['tot_raised']
new_filing.coverage_from_date = results['start_date']
new_filing.coverage_to_date = results['end_date']
new_filing.save()
3
Example 14
Project: fumblerooski Source File: utils.py
def create_weeks(year):
"""
Given a year with games in the db, creates weeks for that year.
"""
min = Game.objects.filter(season=year).aggregate(Min('date'))['date__min']
max = Game.objects.filter(season=year).aggregate(Max('date'))['date__max']
date = min
week = 1
while date <= max:
if date.weekday() < 5:
dd = 5 - date.weekday()
end_date = date + datetime.timedelta(days=dd)
else:
end_date = date
new_week, created = Week.objects.get_or_create(season=min.year, week_num = week, end_date = end_date)
date += datetime.timedelta(days=7)
week += 1
3
Example 15
Project: neo4django Source File: nodequeryset_tests.py
@with_setup(setup_people, teardown)
def test_aggregate_max_min():
from django.db.models import Max, Min
eq_(Person.objects.all().aggregate(Min('age')).get('age__min', None), 5)
eq_(Person.objects.all().aggregate(Max('age')).get('age__max', None), 30)
eq_(Person.objects.all().filter(name='Candleja-').aggregate(Min('age')).get('age__min', None), 30)
3
Example 16
def save(self, *args, **kwargs):
self.full_clean()
if not self.pk and self.page is not None:
self.ordinal = (self.page.fields.aggregate(
Max("ordinal")
)["ordinal__max"] or 0) + 1
return super(Field, self).save(*args, **kwargs)
3
Example 17
def get_next_reference(self):
try:
# Very dirty hack, but kinda works for reference (i.e. it doesn't
# have to be unique)
next_ref = SaleOrder.objects.all().aggregate(
models.Max('id'))['id__max'] + 1
except:
next_ref = 1
full_ref = '%.5d/%s' % (next_ref, str(str(ttime() * 10)[8:-2]))
return full_ref
3
Example 18
Project: djep Source File: models.py
def get_next_product_number(self):
"""Returns the next product number."""
if self.count() > 0:
last = self.aggregate(models.Max('product_number'))
return last['product_number__max'] + 1
else:
return settings.PRODUCT_NUMBER_START
3
Example 19
def get_or_assign_number(self):
if self.number is None:
aggr = Customer.objects.filter(number__isnull=False).aggregate(models.Max('number'))
self.number = (aggr['number__max'] or 0) + 1
self.save()
return self.get_number()
3
Example 20
Project: django-billing Source File: models.py
def filter_by_current_statuses(self, statuses):
"""
returns the subscriptions whose most recent status is
one of those specified
"""
annotated = self.annotate(
newest=models.Max('approval_statuses__created'))
newest_subs = annotated.filter(
approval_statuses__created=models.F('newest'),
approval_statuses__status__in=statuses
)
return newest_subs
3
Example 21
def test_aggregate_multi_join(self):
vals = Store.objects.aggregate(Max("books__authors__age"))
self.assertEqual(len(vals), 1)
self.assertEqual(vals["books__authors__age__max"], 57)
vals = Author.objects.aggregate(Min("book__publisher__num_awards"))
self.assertEqual(len(vals), 1)
self.assertEqual(vals["book__publisher__num_awards__min"], 1)
3
Example 22
Project: doc-versions Source File: models.py
@classmethod
def bulk_ids(cls, n):
assert n >= 0
if n == 0:
return []
if 'postgresql' in settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE']:
cursor = connection.cursor()
sql = "select nextval('%s_id_seq') from generate_series(1,%d)"\
% (cls._meta.db_table, n)
cursor.execute(sql)
return [int(r[0]) for r in cursor]
elif 'sqlite' in settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE']:
m = cls.objects.aggregate(models.Max('id'))['id__max']
if m is None:
m = 0
return range(m + 1, n + m + 1)
raise NotImplementedError
3
Example 23
def get_or_assign_number(self):
"""
Set a unique number to identify this Order object. The first 4 digits represent the
current year. The last five digits represent a zero-padded incremental counter.
"""
if self.number is None:
epoch = timezone.now().date()
epoch = epoch.replace(epoch.year, 1, 1)
aggr = Order.objects.filter(number__isnull=False, created_at__gt=epoch).aggregate(models.Max('number'))
try:
epoc_number = int(str(aggr['number__max'])[4:]) + 1
self.number = int('{0}{1:05d}'.format(epoch.year, epoc_number))
except (KeyError, ValueError):
# the first order this year
self.number = int('{0}00001'.format(epoch.year))
return self.get_number()
3
Example 24
@skipUnlessDBFeature('can_distinct_on_fields')
def test_distinct_not_implemented_checks(self):
# distinct + annotate not allowed
with self.assertRaises(NotImplementedError):
Celebrity.objects.annotate(Max('id')).distinct('id')[0]
with self.assertRaises(NotImplementedError):
Celebrity.objects.distinct('id').annotate(Max('id'))[0]
# However this check is done only when the query executes, so you
# can use distinct() to remove the fields before execution.
Celebrity.objects.distinct('id').annotate(Max('id')).distinct()[0]
# distinct + aggregate not allowed
with self.assertRaises(NotImplementedError):
Celebrity.objects.distinct('id').aggregate(Max('id'))
3
Example 25
def get(self, request, *args, **kwargs):
result = dict(
num_rows=Citizen.objects.count(),
)
if result['num_rows']:
result.update(
**Citizen.objects.aggregate(max_id=Max('national_id'), min_id=Min('national_id'))
)
try:
metadata = CitizenMetadata.objects.get()
except CitizenMetadata.DoesNotExist:
pass
else:
result['dump_date'] = format_datetime(metadata.dump_time)
return self.render_json_response(result)
3
Example 26
Project: site Source File: contests.py
def get_participation_ranking_profile(contest, participation, problems):
scoring = {data['id']: (data['score'], data['time']) for data in
contest.contest_problems.filter(submission__participation=participation)
.annotate(score=Max('submission__points'), time=Max('submission__submission__date'))
.values('score', 'time', 'id')}
return make_contest_ranking_profile(participation, [
BestSolutionData(code=problem.problem.code, points=scoring[problem.id][0],
time=scoring[problem.id][1] - participation.start,
state=best_solution_state(scoring[problem.id][0], problem.points))
if problem.id in scoring else None for problem in problems
])
3
Example 27
def test_distinct_not_implemented_checks(self):
# distinct + annotate not allowed
with self.assertRaises(NotImplementedError):
Celebrity.objects.annotate(Max('id')).distinct('id')[0]
with self.assertRaises(NotImplementedError):
Celebrity.objects.distinct('id').annotate(Max('id'))[0]
# However this check is done only when the query executes, so you
# can use distinct() to remove the fields before execution.
Celebrity.objects.distinct('id').annotate(Max('id')).distinct()[0]
# distinct + aggregate not allowed
with self.assertRaises(NotImplementedError):
Celebrity.objects.distinct('id').aggregate(Max('id'))
3
Example 28
Project: gnotty Source File: gnotty_tags.py
@register.inclusion_tag("gnotty/includes/nav.html", takes_context=True)
def gnotty_nav(context):
min_max = IRCMessage.objects.aggregate(Min("message_time"),
Max("message_time"))
if min_max.values()[0]:
years = range(min_max["message_time__max"].year,
min_max["message_time__min"].year - 1, -1)
else:
years = []
context["IRC_CHANNEL"] = settings.IRC_CHANNEL
context["years"] = years
context["LOGOUT_URL"] = django_settings.LOGOUT_URL
return context
3
Example 29
Project: django-newsletter Source File: models.py
def get_next_article_sortorder(self):
""" Get next available sortorder for Article. """
next_order = self.articles.aggregate(
models.Max('sortorder')
)['sortorder__max']
if next_order:
return next_order + 10
else:
return 10
3
Example 30
Project: pari Source File: common.py
def get_random_entries(model, count=1):
max_id = model.objects.aggregate(Max('id'))['id__max']
if max_id:
i = 0
while i < count:
try:
yield model.objects.get(pk=randint(1, max_id))
i += 1
except model.DoesNotExist:
pass
else:
pass
3
Example 31
Project: fumblerooski Source File: utils.py
def next_coach_id():
"""
Generates the next id for newly added coaches, since their slugs (which combine the id and name fields)
are added post-commit.
"""
c = Coach.objects.aggregate(Max("id"))
return c['id__max']+1
3
Example 32
Project: read_FEC Source File: mark_superceded_body_rows.py
def summarize_nonquarterly_f5(new_filing):
filing_ies = SkedE.objects.filter(filing_number=new_filing.filing_number)
results = filing_ies.aggregate(start_date=Min('expenditure_date_formatted'), end_date=Max('expenditure_date_formatted'))
new_filing.coverage_from_date = results['start_date']
new_filing.coverage_to_date = results['end_date']
new_filing.save()
3
Example 33
Project: open-context-py Source File: models.py
def get_manifest_project_dates(self):
"""
gets initial publication date for items in the manifest
"""
projs = Manifest.objects.values_list('project_uuid').distinct()
proj_dates = {}
from django.utils import timezone
start_date = timezone.now()
for proj in projs:
early_date = Manifest.objects.filter(project_uuid=proj[0],
published__isnull=False,
published__lte=start_date).aggregate(earliest=Min('published'),
last=Max('published'))
proj_dates[proj[0]] = early_date
return proj_dates
3
Example 34
def save(self, commit=True):
self.instance.product_name = self.cleaned_data['product_name']
self.instance.caption = self.cleaned_data['caption']
self.instance.slug = self.cleaned_data['slug']
max_order = Commodity.objects.aggregate(max=Max('order'))['max']
self.instance.order = max_order + 1 if max_order else 1
commodity = super(CommodityWizardForm, self).save(commit)
ProductPageModel.objects.create(product=commodity, page=self.page.get_public_object())
return commodity
3
Example 35
Project: open-context-py Source File: math.py
def get_date_range(self, predicate_uuids):
if not isinstance(predicate_uuids, list):
predicate_uuids = [str(predicate_uuids)]
sum_ass = Assertion.objects\
.filter(predicate_uuid__in=predicate_uuids)\
.aggregate(Min('data_date'),
Max('data_date'),
Count('hash_id'))
output = {}
output['min'] = sum_ass['data_date__min']
output['max'] = sum_ass['data_date__max']
output['count'] = sum_ass['hash_id__count']
return output
3
Example 36
Project: pootle Source File: utils.py
@property
def aggregate_max_fields(self):
return list(
models.Max(f)
for f
in self.max_fields)
3
Example 37
Project: ella Source File: test_models.py
def test_render_position_with_invalid_target_returns_empty(self):
target_ct = ContentType.objects.get_for_model(ContentType)
invalid_id = ContentType.objects.aggregate(Max('id'))['id__max'] + 1
p = Position.objects.create(category=self.category, name='position-name', text='some text', target_ct=target_ct, target_id=invalid_id)
tools.assert_equals('', p.render(Context({}), NodeList(), ''))
3
Example 38
def save(self, *args, **kwargs):
self.slug = None # regerate slug so import format stays in sync
if self.position == 0:
others = ActivityComponent.objects.filter(numeric_activity=self.numeric_activity).exclude(pk=self.pk)
maxpos = others.aggregate(models.Max('position'))['position__max']
if maxpos:
self.position = maxpos + 1
else:
self.position = 1
super(ActivityComponent, self).save(*args, **kwargs)
3
Example 39
Project: djep Source File: check_invoice_number.py
def handle(self, *args, **options):
max_in_db = models.Purchase.objects\
.filter(conference=current_conference())\
.aggregate(Max('invoice_number'))\
.get('invoice_number__max', 0)
redis = get_redis_connection()
redis_value = redis.get(settings.INVOICE_NUMBER_SEQUENCE_NAME)
if redis_value is None:
redis_value = 0
else:
redis_value = int(redis_value)
if redis_value != max_in_db:
print("Sequence stored in Redis is different from latest invoice in database: {0} vs. {1}".format(
redis_value, max_in_db), file=sys.stderr)
sys.exit(1)
else:
print("OK")
3
Example 40
def bottom(self, extra_update=None):
"""
Move this object to the bottom of the ordered stack.
"""
o = self.get_ordering_queryset().aggregate(Max(self.order_field_name)).get(self.order_field_name + '__max')
self.to(o, extra_update=extra_update)
3
Example 41
Project: djep Source File: tests.py
def get_next_invoice_number():
def wrapper(sequence_name=None):
last = models.Purchase.objects.aggregate(last=Max('invoice_number'))['last']
if last is None:
return 1
else:
return last + 1
return wrapper
3
Example 42
def save(self, *args, **kwargs):
if not self.pk:
max_ordinal = self.survey.questions.aggregate(
Max("ordinal")
)["ordinal__max"] or 0
self.ordinal = max_ordinal + 1
return super(SurveyQuestion, self).save(*args, **kwargs)
3
Example 43
def refresh_updates(self):
redis = get_redis_connection()
last_updates = self.last_updates()
urls = self.feeds.values_list('pk', 'url')
for pk, url in urls:
if url in last_updates:
continue
value = self.entries.filter(feed_id=pk).aggregate(
date=Max('date'))['date']
value = float(value.strftime('%s')) if value else 0
redis.zadd(self.last_update_key, url, value)
return self.last_updates()
3
Example 44
Project: django-calendartools Source File: base.py
@property
def calendar_bounds(self):
return self.calendar.occurrences.visible().aggregate(
earliest_occurrence=Min('start'),
latest_occurrence=Max('finish'),
)
3
Example 45
Project: oioioi Source File: models.py
def _round_end_date_name_generator(obj):
max_round_extension = RoundTimeExtension.objects.filter(round=obj). \
aggregate(Max('extra_time'))['extra_time__max']
if max_round_extension is not None:
return ungettext("End of %(name)s (+ %(ext)d min)",
"End of %(name)s (+ %(ext)d mins)",
max_round_extension) % \
{'name': obj.name, 'ext': max_round_extension}
else:
return _("End of %s") % obj.name
3
Example 46
def run():
need_renewal = InstagramInfo.objects.values('user').annotate(
Max('end_date')).filter(end_date__lte=datetime.now())
with open('users.csv', 'w') as csvfile:
csvwriter = csv.writer(csvfile)
for info in need_renewal:
u = User.objects.get(id=info['user'])
full_name = InstagramInfo.objects.filter(user=u)[0].full_name
csvwriter.writerow([u.email, full_name])
print "Wrote results to users.csv"
3
Example 47
Project: djangopackages Source File: context_processors.py
def core_values(request):
"""
A nice pun. But this is how we stick handy data everywhere.
"""
data = {
'SITE_TITLE': getattr(settings, "SITE_TITLE", "Django Packages"),
'FRAMEWORK_TITLE': getattr(settings, "FRAMEWORK_TITLE", "Django"),
'MAX_WEIGHT': SearchV2.objects.all().aggregate(Max('weight'))['weight__max']
}
return data
3
Example 48
Project: reviewboard Source File: models.py
@staticmethod
def compute_next_display_position(review_request):
"""Compute the display position for a new FileAttachmentHistory."""
# Right now, display_position is monotonically increasing for each
# review request. In the future this might be extended to allow the
# user to change the order of attachments on the page.
max_position = (
FileAttachmentHistory.objects
.filter(review_request=review_request)
.aggregate(Max('display_position'))
.get('display_position__max')) or 0
return max_position + 1
3
Example 49
Project: SmartElect Source File: factories.py
def get_unused_gender_appropriate_national_id(stub):
if stub.gender == MALE:
min_nid = 100000000000
max_nid = 199999999999
else:
min_nid = 200000000000
max_nid = 299999999999
# Find the max nid in use in the desired range, among Citizens.
max_citizen_nid = Citizen.objects.unfiltered()\
.filter(national_id__gte=min_nid, national_id__lte=max_nid)\
.aggregate(max=Max('national_id'))['max'] \
or min_nid - 1
# Use the next one, or the first one in the desired range
return max(1 + max_citizen_nid, min_nid)
3
Example 50
Project: silk Source File: summary.py
def _longest_query_by_view(self, filters):
values_list = models.Request.objects.filter(*filters).values_list("view_name").annotate(max=Max('time_taken')).order_by('-max')[:5]
requests = []
for view_name, _ in values_list:
request = models.Request.objects.filter(view_name=view_name, *filters).order_by('-time_taken')[0]
requests.append(request)
return requests