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.
230 Examples
3
Source : models.py
with GNU Affero General Public License v3.0
from 17thshard
with GNU Affero General Public License v3.0
from 17thshard
def set_order_last(self):
if Entry.objects.filter(event=self.event).exists():
self.order = Entry.objects.filter(event=self.event).aggregate(Max('order'))[
'order__max'] + 1
else:
self.order = 0
@staticmethod
3
Source : querysets.py
with Mozilla Public License 2.0
from Amsterdam
with Mozilla Public License 2.0
from Amsterdam
def reporter_feedback_count(self, email, is_satisfied=True):
return self.filter_reporter(
email=email
).annotate(
feedback_count=Count('feedback')
).filter(
feedback_count__gte=1
).annotate(
feedback_max_created_at=Max('feedback__created_at'),
feedback_max_submitted_at=Max('feedback__submitted_at')
).filter(
feedback__is_satisfied=is_satisfied,
feedback__submitted_at__isnull=False,
feedback__created_at=F('feedback_max_created_at'),
feedback__submitted_at=F('feedback_max_submitted_at')
).count()
def reporter_feedback_satisfied_count(self, email):
3
Source : managers.py
with MIT License
from Arx-Game
with MIT License
from Arx-Game
def annotate_highest_treatment(self, treatment_type, attr_name):
"""This annotates the queryset with the highest value for a given type of treatments"""
from world.conditions.models import TreatmentAttempt
subquery_queryset = (
TreatmentAttempt.objects.filter(
target=OuterRef("pk"),
treatment_type=treatment_type,
uses_remaining__gt=0,
)
.annotate(highest_value=Max("value", output_field=IntegerField(default=0)))
.values("highest_value")[:1]
)
query_kwargs = {
attr_name: Subquery(subquery_queryset, output_field=IntegerField(default=0))
}
return self.annotate(**query_kwargs)
def annotate_recovery_treatment(self):
3
Source : models.py
with MIT License
from auroraresearchlab
with MIT License
from auroraresearchlab
def get_auto_serial(self):
records = Record.objects.filter(zone=self).exclude(type=Record.SOA)
if records:
soa_serial = (
records.aggregate(Max("last_updated"))
.get("last_updated__max")
.timestamp()
)
else:
soa_serial = ceil(datetime.now().timestamp())
if self.last_updated:
soa_serial = ceil(max(soa_serial, self.last_updated.timestamp()))
return soa_serial
def update_serial(self):
3
Source : views.py
with GNU Affero General Public License v3.0
from botshot
with GNU Affero General Public License v3.0
from botshot
def get_last_change(request):
if 'webchat_id' not in request.session:
max_timestamp = 0
else:
webchat_id = request.session['webchat_id']
max_timestamp = _get_webchat_id_messages(webchat_id).aggregate(Max('time')).get('time__max')
max_timestamp = max_timestamp.timestamp() if max_timestamp else 0
return JsonResponse({'timestamp': max_timestamp})
3
Source : signals.py
with Apache License 2.0
from cas-packone
with Apache License 2.0
from cas-packone
def monitor_group(sender, instance, **kwargs):
if sender==Instance:
if instance.deleting: return
for group in instance.group_set.all():
status=group.instances.all().aggregate(Max('status'))['status__max']#TODO use join
Group.objects.filter(pk=group.pk).update(status=status)
group.refresh_from_db()
monitored.send(sender=Group, instance=group, name='monitored')
else:
if instance.status==OPERATION_STATUS.waiting.value: return
instance.target.monitor()
@receiver(post_save, sender=InstanceOperation)
3
Source : signals.py
with Apache License 2.0
from cas-packone
with Apache License 2.0
from cas-packone
def monitor_status(sender, instance, **kwargs):
if sender==Group:
if instance.deleting: return
for cluster in instance.cluster_set.all():
status=cluster.steps.all().aggregate(Max('status'))['status__max']
models.Cluster.objects.filter(pk=cluster.pk).update(status=status)
cluster.refresh_from_db()
monitored.send(sender=models.Cluster, instance=cluster, name='monitored')
else:
if instance.status==OPERATION_STATUS.waiting.value: return
else:
instance.target.monitor()
post_save.connect(tidy_operation,sender=models.ClusterOperation)
3
Source : v1_integration_test.py
with MIT License
from cc-archive
with MIT License
from cc-archive
def test_auth_email_verification(test_auth_token_exchange, django_db_setup):
# This test needs to cheat by looking in the database, so it will be
# skipped in non-local environments.
if API_URL == 'http://localhost:8000':
_id = OAuth2Verification.objects.aggregate(Max('id'))['id__max']
verify = OAuth2Verification.objects.get(id=_id)
code = verify.code
path = reverse('verify-email', args=[code])
url = f'{API_URL}{path}'
response = requests.get(url)
assert response.status_code == 200
test_auth_rate_limit_reporting(
test_auth_token_exchange, verified=True
)
@pytest.mark.skip(reason="Unmaintained feature/grequests ssl recursion bug")
3
Source : result.py
with GNU General Public License v3.0
from codexgigassys
with GNU General Public License v3.0
from codexgigassys
def max_elapsed_time(self) -> int:
max_elapsed_time = self.decompiled().aggregate(Max('elapsed_time'))['elapsed_time__max']
return max_elapsed_time if max_elapsed_time is not None else 0
class Result(models.Model):
3
Source : serializers.py
with MIT License
from coreybobco
with MIT License
from coreybobco
def get_most_stacked_setlist(self, obj):
annotated_setlist_qs = obj.setlists.all().annotate(Count('tracks'))
max_num_tracks = annotated_setlist_qs.aggregate(Max('tracks__count'))['tracks__count__max']
if max_num_tracks > 0:
most_stacked_setlist = annotated_setlist_qs.filter(tracks__count=max_num_tracks).first()
setlist_context = self.context
setlist_context['num_tracks'] = max_num_tracks
return SetlistSerializer(context=self.context).to_representation(instance=most_stacked_setlist)
return None
def get_top_played_artists(self, obj):
3
Source : models.py
with MIT License
from elton2048
with MIT License
from elton2048
def save(self, *args, **kwargs):
if self.pk is None:
sort_order_max = self.__class__.objects.aggregate(Max('sort_order'))['sort_order__max'] or 0
self.sort_order = sort_order_max + 1
super().save(*args, **kwargs)
class Meta:
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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)
def test_aggregate_alias(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_values_aggregation(self):
# Refs #20782
max_rating = Book.objects.values('rating').aggregate(max_rating=Max('rating'))
self.assertEqual(max_rating['max_rating'], 5)
max_books_per_rating = Book.objects.values('rating').annotate(
books_per_rating=Count('id')
).aggregate(Max('books_per_rating'))
self.assertEqual(
max_books_per_rating,
{'books_per_rating__max': 3})
def test_ticket17424(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_nonfield_annotation(self):
book = Book.objects.annotate(val=Max(Value(2, output_field=IntegerField()))).first()
self.assertEqual(book.val, 2)
book = Book.objects.annotate(val=Max(Value(2), output_field=IntegerField())).first()
self.assertEqual(book.val, 2)
book = Book.objects.annotate(val=Max(2, output_field=IntegerField())).first()
self.assertEqual(book.val, 2)
def test_missing_output_field_raises_error(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_annotated_aggregate_over_annotated_aggregate(self):
with self.assertRaisesMessage(FieldError, "Cannot compute Sum('id__max'): 'id__max' is an aggregate"):
Book.objects.annotate(Max('id')).annotate(Sum('id__max'))
class MyMax(Max):
def as_sql(self, compiler, connection):
self.set_source_expressions(self.get_source_expressions()[0:1])
return super(MyMax, self).as_sql(compiler, connection)
with self.assertRaisesMessage(FieldError, "Cannot compute Max('id__max'): 'id__max' is an aggregate"):
Book.objects.annotate(Max('id')).annotate(my_max=MyMax('id__max', 'price'))
def test_multi_arg_aggregate(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_complex_values_aggregation(self):
max_rating = Book.objects.values('rating').aggregate(
double_max_rating=Max('rating') + Max('rating'))
self.assertEqual(max_rating['double_max_rating'], 5 * 2)
max_books_per_rating = Book.objects.values('rating').annotate(
books_per_rating=Count('id') + 5
).aggregate(Max('books_per_rating'))
self.assertEqual(
max_books_per_rating,
{'books_per_rating__max': 3 + 5})
def test_expression_on_aggregation(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_field_error(self):
# Bad field requests in aggregates are caught and reported
with self.assertRaises(FieldError):
Book.objects.all().aggregate(num_authors=Count('foo'))
with self.assertRaises(FieldError):
Book.objects.all().annotate(num_authors=Count('foo'))
with self.assertRaises(FieldError):
Book.objects.all().annotate(num_authors=Count('authors__id')).aggregate(Max('foo'))
def test_more(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
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'))
def test_distinct_on_in_ordered_subquery(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_annotate_with_aggregation_in_value(self):
self.assertQuerysetEqual(
CaseTestModel.objects.values(*self.non_lob_fields).annotate(
min=Min('fk_rel__integer'),
max=Max('fk_rel__integer'),
).annotate(
test=Case(
When(integer=2, then='min'),
When(integer=3, then='max'),
),
).order_by('pk'),
[(1, None, 1, 1), (2, 2, 2, 3), (3, 4, 3, 4), (2, 2, 2, 3), (3, 4, 3, 4), (3, 4, 3, 4), (4, None, 5, 5)],
transform=itemgetter('integer', 'test', 'min', 'max')
)
def test_annotate_with_aggregation_in_condition(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_annotate_with_aggregation_in_condition(self):
self.assertQuerysetEqual(
CaseTestModel.objects.values(*self.non_lob_fields).annotate(
min=Min('fk_rel__integer'),
max=Max('fk_rel__integer'),
).annotate(
test=Case(
When(integer2=F('min'), then=Value('min')),
When(integer2=F('max'), then=Value('max')),
output_field=models.CharField(),
),
).order_by('pk'),
[(1, 1, 'min'), (2, 3, 'max'), (3, 4, 'max'), (2, 2, 'min'), (3, 4, 'max'), (3, 3, 'min'), (4, 5, 'min')],
transform=itemgetter('integer', 'integer2', 'test')
)
def test_annotate_with_aggregation_in_predicate(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_annotate_with_aggregation_in_predicate(self):
self.assertQuerysetEqual(
CaseTestModel.objects.values(*self.non_lob_fields).annotate(
max=Max('fk_rel__integer'),
).annotate(
test=Case(
When(max=3, then=Value('max = 3')),
When(max=4, then=Value('max = 4')),
default=Value(''),
output_field=models.CharField(),
),
).order_by('pk'),
[(1, 1, ''), (2, 3, 'max = 3'), (3, 4, 'max = 4'), (2, 3, 'max = 3'),
(3, 4, 'max = 4'), (3, 4, 'max = 4'), (4, 5, '')],
transform=itemgetter('integer', 'max', 'test')
)
def test_annotate_exclude(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_filter_with_aggregation_in_value(self):
self.assertQuerysetEqual(
CaseTestModel.objects.values(*self.non_lob_fields).annotate(
min=Min('fk_rel__integer'),
max=Max('fk_rel__integer'),
).filter(
integer2=Case(
When(integer=2, then='min'),
When(integer=3, then='max'),
),
).order_by('pk'),
[(3, 4, 3, 4), (2, 2, 2, 3), (3, 4, 3, 4)],
transform=itemgetter('integer', 'integer2', 'min', 'max')
)
def test_filter_with_aggregation_in_condition(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_filter_with_aggregation_in_condition(self):
self.assertQuerysetEqual(
CaseTestModel.objects.values(*self.non_lob_fields).annotate(
min=Min('fk_rel__integer'),
max=Max('fk_rel__integer'),
).filter(
integer=Case(
When(integer2=F('min'), then=2),
When(integer2=F('max'), then=3),
),
).order_by('pk'),
[(3, 4, 3, 4), (2, 2, 2, 3), (3, 4, 3, 4)],
transform=itemgetter('integer', 'integer2', 'min', 'max')
)
def test_filter_with_aggregation_in_predicate(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_filter_with_aggregation_in_predicate(self):
self.assertQuerysetEqual(
CaseTestModel.objects.values(*self.non_lob_fields).annotate(
max=Max('fk_rel__integer'),
).filter(
integer=Case(
When(max=3, then=2),
When(max=4, then=3),
),
).order_by('pk'),
[(2, 3, 3), (3, 4, 4), (2, 2, 3), (3, 4, 4), (3, 3, 4)],
transform=itemgetter('integer', 'integer2', 'max')
)
def test_update(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_annotation_with_callable_default(self):
# Happening.when has a callable default of datetime.datetime.now.
qs = Happening.objects.annotate(latest_time=models.Max('when'))
self.assert_pickles(qs)
def test_missing_django_version_unpickling(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_query_aggregation(self):
# Only min and max make sense for datetimes.
Event.objects.create(dt=datetime.datetime(2011, 9, 1, 23, 20, 20))
Event.objects.create(dt=datetime.datetime(2011, 9, 1, 13, 20, 30))
Event.objects.create(dt=datetime.datetime(2011, 9, 1, 3, 20, 40))
result = Event.objects.all().aggregate(Min('dt'), Max('dt'))
self.assertEqual(result, {
'dt__min': datetime.datetime(2011, 9, 1, 3, 20, 40),
'dt__max': datetime.datetime(2011, 9, 1, 23, 20, 20),
})
def test_query_annotation(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_query_aggregation(self):
# Only min and max make sense for datetimes.
Event.objects.create(dt=datetime.datetime(2011, 9, 1, 23, 20, 20, tzinfo=EAT))
Event.objects.create(dt=datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT))
Event.objects.create(dt=datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT))
result = Event.objects.all().aggregate(Min('dt'), Max('dt'))
self.assertEqual(result, {
'dt__min': datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT),
'dt__max': datetime.datetime(2011, 9, 1, 23, 20, 20, tzinfo=EAT),
})
def test_query_annotation(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_update_annotated_queryset(self):
"""
Update of a queryset that's been annotated.
"""
# Trivial annotated update
qs = DataPoint.objects.annotate(alias=F('value'))
self.assertEqual(qs.update(another_value='foo'), 3)
# Update where annotation is used for filtering
qs = DataPoint.objects.annotate(alias=F('value')).filter(alias='apple')
self.assertEqual(qs.update(another_value='foo'), 1)
# Update where annotation is used in update parameters
qs = DataPoint.objects.annotate(alias=F('value'))
self.assertEqual(qs.update(another_value=F('alias')), 3)
# Update where aggregation annotation is used in update parameters
qs = DataPoint.objects.annotate(max=Max('value'))
with self.assertRaisesMessage(FieldError, 'Aggregate functions are not allowed in this query'):
qs.update(another_value=F('max'))
def test_update_annotated_multi_table_queryset(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_update_annotated_multi_table_queryset(self):
"""
Update of a queryset that's been annotated and involves multiple tables.
"""
# Trivial annotated update
qs = DataPoint.objects.annotate(related_count=Count('relatedpoint'))
self.assertEqual(qs.update(value='Foo'), 3)
# Update where annotation is used for filtering
qs = DataPoint.objects.annotate(related_count=Count('relatedpoint'))
self.assertEqual(qs.filter(related_count=1).update(value='Foo'), 1)
# Update where annotation is used in update parameters
# #26539 - This isn't forbidden but also doesn't generate proper SQL
# qs = RelatedPoint.objects.annotate(data_name=F('data__name'))
# updated = qs.update(name=F('data_name'))
# self.assertEqual(updated, 1)
# Update where aggregation annotation is used in update parameters
qs = RelatedPoint.objects.annotate(max=Max('data__value'))
with self.assertRaisesMessage(FieldError, 'Aggregate functions are not allowed in this query'):
qs.update(name=F('max'))
3
Source : clan.py
with MIT License
from gogaz
with MIT License
from gogaz
def clan_members(request, tag):
try:
clan = Clan.objects.get(tag=tag)
except Clan.DoesNotExist:
return not_found_error("clan", tag)
if request.method == 'GET':
latest_stats_history_pks = PlayerClanStatsHistory.objects.values('player')\
.annotate(max_id=models.Max('id')).values_list('max_id', flat=True)
players = clan.get_players()\
.prefetch_related(models.Prefetch('playerstatshistory_set',
queryset=PlayerClanStatsHistory.objects.filter(pk__in=latest_stats_history_pks),
to_attr='last_stat_list'))
serializer = PlayerClanDetailsSerializer(players, many=True)
return Response(serializer.data)
@api_view(['GET', 'POST'])
3
Source : online_blog.py
with Apache License 2.0
from goutomroy
with Apache License 2.0
from goutomroy
def annotation_test(self):
# q = Book.objects.filter(publisher__name='Shroff')
# q = Book.objects.annotate(num_authors=Count('authors'))
q = Book.objects.aggregate(price_diff=
Max('price', output_field=FloatField()) -
Avg('price', output_field=FloatField()))
logger.info(q)
def handle(self, *args, **options):
3
Source : models.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
def updated(self):
min_time = datetime.datetime(1970, 1, 1, 0, 0, 0) # should be Meeting.modified, but we don't have that
timeslots_updated = self.timeslot_set.aggregate(Max('modified'))["modified__max"] or min_time
sessions_updated = self.session_set.aggregate(Max('modified'))["modified__max"] or min_time
assignments_updated = min_time
if self.schedule:
assignments_updated = SchedTimeSessAssignment.objects.filter(schedule__in=[self.schedule, self.schedule.base if self.schedule else None]).aggregate(Max('modified'))["modified__max"] or min_time
ts = max(timeslots_updated, sessions_updated, assignments_updated)
tz = pytz.timezone(settings.PRODUCTION_TIMEZONE)
ts = tz.localize(ts)
return ts
@memoize
3
Source : tests.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
def test_remove_invalid_position(self):
no_such_position_id = self.nc.position_set.aggregate(Max('id'))['id__max']+1
url = reverse('ietf.nomcom.views.remove_position',kwargs={'year':self.nc.year(),'position_id':no_such_position_id})
login_testing_unauthorized(self,self.chair.user.username,url)
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def test_edit_position(self):
3
Source : tests.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
def test_edit_invalid_position(self):
no_such_position_id = self.nc.position_set.aggregate(Max('id'))['id__max']+1
url = reverse('ietf.nomcom.views.edit_position',kwargs={'year':self.nc.year(),'position_id':no_such_position_id})
login_testing_unauthorized(self,self.chair.user.username,url)
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def test_edit_nominee(self):
3
Source : views.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
def get_next_order_num(session):
'''
This function takes a session object and returns the
next slide order number to use for a newly added slide as an integer.
'''
max_order = session.materials.aggregate(Max('order'))['order__max']
return max_order + 1 if max_order else 1
def parsedate(d):
3
Source : views.py
with Apache License 2.0
from janw
with Apache License 2.0
from janw
def get_queryset(self, **kwargs):
user_ordering = self.request.user.listener.sort_order_podcasts
queryset = (
Podcast.objects.prefetch_related("subscribers", "subscribers")
.prefetch_related("followers", "followers")
.annotate(num_episodes=Count("episodes"))
.annotate(
downloaded_episodes=Count(
Case(When(episodes__downloaded__isnull=False, then=1))
)
)
.annotate(last_episode_date=Max("episodes__published"))
.filter(followers=self.request.user.listener)
.order_by(user_ordering)
)
return queryset
def get_context_data(self, **kwargs):
3
Source : update_texting_history.py
with GNU General Public License v3.0
from JustFixNYC
with GNU General Public License v3.0
from JustFixNYC
def get_min_max_date_sent(
queryset,
) -> Tuple[Optional[datetime.datetime], Optional[datetime.datetime]]:
result = queryset.aggregate(Min("date_sent"), Max("date_sent"))
return (result["date_sent__min"], result["date_sent__max"])
def stop_when_older_than(msgs: MessageIterator, when: datetime.datetime) -> MessageIterator:
3
Source : models.py
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
def save(self, *args, **kwargs):
if self.sort_order is None:
qs = self.get_ordering_queryset()
existing_max = qs.aggregate(Max('sort_order'))
existing_max = existing_max.get('sort_order__max')
self.sort_order = 0 if existing_max is None else existing_max + 1
super().save(*args, **kwargs)
def delete(self, *args, **kwargs):
3
Source : models.py
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
with BSD 3-Clause "New" or "Revised" License
from Kenstogram
def save(self, *args, **kwargs):
"""Assign an auto incremented value as a fulfillment order."""
if not self.pk:
groups = self.order.fulfillments.all()
existing_max = groups.aggregate(Max('fulfillment_order'))
existing_max = existing_max.get('fulfillment_order__max')
self.fulfillment_order = (
existing_max + 1 if existing_max is not None else 1)
return super().save(*args, **kwargs)
@property
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_aggrate_annotation(self):
# Aggregates can be composed over annotations.
# The return type is derived from the composed aggregate
vals = Book.objects.all().annotate(num_authors=Count('authors__id')).aggregate(Max('pages'), Max('price'), Sum('num_authors'), Avg('num_authors'))
self.assertEqual(vals, {
'num_authors__sum': 10,
'num_authors__avg': Approximate(1.666, places=2),
'pages__max': 1132,
'price__max': Decimal("82.80")
})
def test_field_error(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_field_error(self):
# Bad field requests in aggregates are caught and reported
self.assertRaises(
FieldError,
lambda: Book.objects.all().aggregate(num_authors=Count('foo'))
)
self.assertRaises(
FieldError,
lambda: Book.objects.all().annotate(num_authors=Count('foo'))
)
self.assertRaises(
FieldError,
lambda: Book.objects.all().annotate(num_authors=Count('authors__id')).aggregate(Max('foo'))
)
def test_more(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
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
Source : api.py
with MIT License
from mangadventure
with MIT License
from mangadventure
def get_queryset(self) -> QuerySet:
q = Q(chapters__published__lte=tz.now())
return models.Series.objects.annotate(
chapter_count=Count('chapters', filter=q),
latest_upload=Max('chapters__published'),
views=Sum('chapters__views', distinct=True)
).filter(chapter_count__gt=0).distinct()
def get_serializer_class(self) -> Type[serializers.SeriesSerializer]:
3
Source : models.py
with GNU General Public License v3.0
from Mercado-Social-de-Madrid
with GNU General Public License v3.0
from Mercado-Social-de-Madrid
def new_idtpv(self):
new_idtpv = '%d' % (int(self.all().aggregate(Max('idtpv')).get('idtpv__max') or '1000000000'[:10])+1)
self.create(idtpv=new_idtpv)
return new_idtpv
class SermepaIdTPV(models.Model):
3
Source : core.py
with Apache License 2.0
from netsec-ethz
with Apache License 2.0
from netsec-ethz
def certificates_latest(self):
""" returns a queryset of all the latest certificates of this AS """
certs = Certificate.objects.none()
for key_usage in Key.USAGES:
latest_version = self.keys.filter(usage=key_usage).aggregate(models.Max('version'))[
'version__max'] or 1
certs = certs | Certificate.objects.filter(key__AS=self, key__usage=key_usage,
key__version__gte=latest_version)
return certs
def keys_latest(self):
3
Source : core.py
with Apache License 2.0
from netsec-ethz
with Apache License 2.0
from netsec-ethz
def keys_latest(self):
""" returns a queryset of all of the latest keys of this AS """
keys = Key.objects.none()
for key_usage in Key.USAGES:
latest_version = self.keys.filter(usage=key_usage).aggregate(models.Max('version'))[
'version__max'] or 1
keys = keys | Key.objects.filter(AS=self, usage=key_usage,
version__gte=latest_version)
return keys
def validate_crypto(self):
3
Source : pki.py
with Apache License 2.0
from netsec-ethz
with Apache License 2.0
from netsec-ethz
def next_version(as_, usage):
prev = Certificate.objects.filter(key__AS=as_, key__usage=usage).aggregate(
models.Max('version'))['version__max'] or 0
return prev + 1
@receiver(pre_delete, sender=Certificate, dispatch_uid='certificate_delete_callback')
3
Source : user_as.py
with Apache License 2.0
from netsec-ethz
with Apache License 2.0
from netsec-ethz
def _max_id(self):
"""
:returns: the max `as_id_int` of all UserASes, or None
"""
return self.aggregate(models.Max('as_id_int')).get('as_id_int__max', None)
class UserAS(AS):
3
Source : changes.py
with GNU General Public License v3.0
from NovaUNL
with GNU General Public License v3.0
from NovaUNL
def plural_modification_for(entity):
"""
Function meant to be used with a last_modified decorator to provide a last change date for a given class.
:param entity: The class being checked.
:return: A function which returns the last modification date.
"""
return lambda request: entity.objects.aggregate(Max('last_save'))['last_save__max']
def last_class_instance_modification(_, instance_id, **kwargs):
3
Source : changes.py
with GNU General Public License v3.0
from NovaUNL
with GNU General Public License v3.0
from NovaUNL
def last_class_question_modification(_, class_id):
# TODO finish, this is not enough to tell if there have been modifications
try:
return \
m.Class.objects.only('last_save').annotate().get(id=class_id).linked_questions.aggregate(Max('timestamp'))[
'timestamp__max']
except m.Class.DoesNotExist:
pass
See More Examples