Here are the examples of the python api django.db.models.F taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
693 Examples
3
Source : views.py
with MIT License
from abrookins
with MIT License
from abrookins
def increment_all_event_versions_with_f_expression():
"""Increment all event versions in the database.
An F() expression can use a single query to update
potentially millions of rows.
"""
Event.objects.all().update(version=F('version') + 1)
# end::increment_all_event_versions_f_expression[]
# tag::update_all_events[]
@login_required
3
Source : mixins.py
with MIT License
from Air-999
with MIT License
from Air-999
def __init__(self, *expressions, ordering=(), **extra):
if not isinstance(ordering, (list, tuple)):
ordering = [ordering]
ordering = ordering or []
# Transform minus sign prefixed strings into an OrderBy() expression.
ordering = (
(OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o)
for o in ordering
)
super().__init__(*expressions, **extra)
self.ordering = self._parse_expressions(*ordering)
def resolve_expression(self, *args, **kwargs):
3
Source : constraints.py
with MIT License
from Air-999
with MIT License
from Air-999
def _get_expression_sql(self, compiler, connection, query):
expressions = []
for expression, operator in self.expressions:
if isinstance(expression, str):
expression = F(expression)
expression = expression.resolve_expression(query=query)
sql, params = expression.as_sql(compiler, connection)
expressions.append('%s WITH %s' % (sql % params, operator))
return expressions
def _get_condition_sql(self, compiler, schema_editor, query):
3
Source : browser_metadata_base.py
with GNU General Public License v3.0
from ajslater
with GNU General Public License v3.0
from ajslater
def _annotate_cover_path(self, queryset, model):
"""Annotate the query set for the coverpath for the sort."""
# Select comics for the children by an outer ref for annotation
# Order the descendant comics by the sort argumentst
if model == Comic:
cover_path = F("cover_path")
else:
order_by = self.get_order_by(model, for_cover_path=True)
cover_path = Subquery(
queryset.filter(pk=OuterRef("pk"))
.order_by(*order_by)
.values("comic__cover_path")[:1]
)
obj_list = queryset.annotate(**{f"{UNIONFIX_PREFIX}cover_path": cover_path})
return obj_list
def _annotate_page_count(self, obj_list):
3
Source : browser_metadata_base.py
with GNU General Public License v3.0
from ajslater
with GNU General Public License v3.0
from ajslater
def _annotate_progress(queryset):
"""Compute progress for each member of a queryset."""
# Requires bookmark and annotation hoisted from userbookmarks.
# Requires page_count native to comic or aggregated
queryset = queryset.annotate(
progress=Coalesce(F("bookmark") * 100.0 / F("page_count"), 0.0)
)
return queryset
def get_aggregate_func(self, field, is_comic_model, autoquery_pk=None):
3
Source : schema.py
with GNU General Public License v3.0
from amfoss
with GNU General Public License v3.0
from amfoss
def resolve_tags(self):
return News.objects.values().annotate(
name=F('tags__name'),
).filter(id=self['id'])
def resolve_cover(self, info):
3
Source : schema.py
with GNU General Public License v3.0
from amfoss
with GNU General Public License v3.0
from amfoss
def resolve_tags(self):
return Blog.objects.values().annotate(
name=F('tags__name'),
).filter(id=self['id'])
def resolve_draft(self, info):
3
Source : schema.py
with GNU General Public License v3.0
from amfoss
with GNU General Public License v3.0
from amfoss
def resolve_photos(self):
return Album.objects.values().annotate(
caption=F('photos__caption'),
image=F('photos__image'),
date=F('photos__date'),
uploader=F('photos__uploader')
).filter(id=self['id'])
class Query(graphene.ObjectType):
3
Source : group.py
with GNU General Public License v3.0
from amfoss
with GNU General Public License v3.0
from amfoss
def resolve_membersCount(self, info):
return Group.objects.annotate(
username=F('members__username')
).filter(id=self['id']).count()
def resolve_admins(self, info):
3
Source : group.py
with GNU General Public License v3.0
from amfoss
with GNU General Public License v3.0
from amfoss
def resolve_admins(self, info):
return Group.objects.values().annotate(
username=F('admins__username'),
first_name=F('admins__first_name'),
last_name=F('admins__last_name'),
date_joined=F('admins__date_joined'),
is_active=F('admins__is_active'),
is_admin=F('admins__is_superuser'),
).filter(id=self['id'])
@graphene.resolve_only_args
3
Source : group.py
with GNU General Public License v3.0
from amfoss
with GNU General Public License v3.0
from amfoss
def resolve_members(self):
return Group.objects.values().annotate(
username=F('members__username'),
first_name=F('members__first_name'),
last_name=F('members__last_name'),
date_joined=F('members__date_joined'),
is_active=F('members__is_active'),
is_admin=F('members__is_superuser'),
).filter(id=self['id'])
class Query(object):
3
Source : profile.py
with GNU General Public License v3.0
from amfoss
with GNU General Public License v3.0
from amfoss
def resolve_languages(self):
return Profile.objects.values().annotate(
name=F('languages__name'),
).filter(id=self['id'])
@login_required
3
Source : project_basic.py
with GNU General Public License v3.0
from amfoss
with GNU General Public License v3.0
from amfoss
def resolve_membersCount(self, info):
return Project.objects.annotate(
username=F('members__username')
).filter(id=self['id']).count()
@graphene.resolve_only_args
3
Source : project_basic.py
with GNU General Public License v3.0
from amfoss
with GNU General Public License v3.0
from amfoss
def resolve_members(self):
return Project.objects.values().annotate(
username=F('members__username'),
first_name=F('members__first_name'),
last_name=F('members__last_name'),
date_joined=F('members__date_joined'),
is_active=F('members__is_active'),
is_admin=F('members__is_superuser'),
).filter(id=self['id'])
@graphene.resolve_only_args
3
Source : project_basic.py
with GNU General Public License v3.0
from amfoss
with GNU General Public License v3.0
from amfoss
def resolve_topics(self):
return Project.objects.values().annotate(
name=F('topics__name'),
type=F('topics__type'),
icon=F('topics__icon')
).filter(id=self['id'])
def resolve_links(self, info):
3
Source : schema.py
with GNU General Public License v3.0
from amfoss
with GNU General Public License v3.0
from amfoss
def resolve_admins(self, info):
return Password.objects.annotate(
username=F('admins__username'),
first_name=F('admins__first_name'),
last_name=F('admins__last_name'),
date_joined=F('admins__date_joined'),
is_active=F('admins__is_active'),
is_admin=F('admins__is_superuser'),
).filter(id=self['id'])
def resolve_url(self, info):
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 : reviews.py
with MIT License
from andreynovikov
with MIT License
from andreynovikov
def get_context_value_from_queryset(self, context, qs):
# select sum(rating * weight) / sum(weight) as average_rating
return qs.aggregate(average_rating=Cast(Sum(F('rating') * F('weight')), FloatField()) /
Cast(Sum(F('weight')), FloatField()))['average_rating']
class RenderRatingAverageNode(RatingAverageNode):
3
Source : views.py
with Apache License 2.0
from aropan
with Apache License 2.0
from aropan
def resources(request):
resources = Resource.objects
resources = resources.select_related('module')
resources = resources.annotate(has_rating_i=Cast('has_rating_history', IntegerField()))
resources = resources.annotate(has_rating_f=Cast('has_rating_i', FloatField()))
resources = resources.annotate(priority=Ln(F('n_contests') + 1) + Ln(F('n_accounts') + 1) + 2 * F('has_rating_f'))
resources = resources.order_by('-priority')
return render(request, 'resources.html', {'resources': resources})
@page_templates((
3
Source : models.py
with Apache License 2.0
from aropan
with Apache License 2.0
from aropan
def update_account_writer(signal, instance, action, reverse, pk_set, **kwargs):
when, action = action.split('_', 1)
if when != 'post':
return
if action == 'add':
delta = 1
elif action == 'remove':
delta = -1
else:
return
if reverse:
instance.n_writers += delta
instance.save()
else:
Account.objects.filter(pk__in=pk_set).update(n_writers=F('n_writers') + delta)
@receiver(m2m_changed, sender=Account.coders.through)
3
Source : models.py
with Apache License 2.0
from aropan
with Apache License 2.0
from aropan
def update_coder_n_accounts_and_n_contests(signal, instance, action, reverse, pk_set, **kwargs):
when, action = action.split('_', 1)
if when != 'post' or action not in ['add', 'remove']:
return
if reverse:
instance.n_accounts = instance.account_set.count()
instance.n_contests = instance.account_set.aggregate(total=Sum('n_contests'))['total'] or 0
instance.save()
else:
Coder.objects.filter(pk__in=pk_set) \
.annotate(n_a=SubqueryCount('account')) \
.annotate(n_c=SubquerySum('account__n_contests')) \
.update(n_accounts=F('n_a'), n_contests=Coalesce('n_c', 0))
class Rating(BaseModel):
3
Source : calculate_coder_n_accounts_and_coder_n_contests.py
with Apache License 2.0
from aropan
with Apache License 2.0
from aropan
def run(*args):
qs = Coder.objects.annotate(count=Count('account')).exclude(n_accounts=F('count'))
total = qs.count()
with tqdm(total=total, desc='calculating n_accounts for coders') as pbar:
with transaction.atomic():
for c in qs.iterator():
c.n_accounts = c.count
c.save()
pbar.update()
qs = Coder.objects.annotate(count=Coalesce(Sum('account__n_contests'), Value(0))).exclude(n_contests=F('count'))
total = qs.count()
with tqdm(total=total, desc='calculating n_contests for coders') as pbar:
with transaction.atomic():
for c in qs.iterator():
c.n_contests = c.count
c.save()
pbar.update()
3
Source : set-account-ratings.py
with Apache License 2.0
from aropan
with Apache License 2.0
from aropan
def run(*args):
accounts = Account.objects
qs = accounts.filter(info__rating__isnull=False)
qs = qs.annotate(info_rating=Cast(JSONF('info__rating'), IntegerField()))
qs = qs.exclude(rating=F('info_rating'))
ret = qs.update(rating=F('info_rating'))
print(ret)
qs = accounts.filter(rating__isnull=False)
qs = qs.annotate(r50=F('rating') / 50)
qs = qs.exclude(rating50=F('r50'))
ret = qs.update(rating50=F('r50'))
print(ret)
3
Source : models.py
with Apache License 2.0
from aropan
with Apache License 2.0
from aropan
def get_ordered_resources(self):
return Resource.objects \
.annotate(n=SubquerySum('account__n_contests', filter=Q(coders=self))) \
.order_by(F('n').desc(nulls_last=True), '-has_rating_history', '-n_contests')
@property
3
Source : user_attendance.py
with GNU General Public License v3.0
from auto-mat
with GNU General Public License v3.0
from auto-mat
def get_frequency_rank_in_team(self):
return (
self.team.members.order_by(
F("frequency").desc(nulls_last=True),
"get_rides_count_denorm",
)
.filter(frequency__gte=self.frequency - 0.000000001)
.count()
)
# Frequency returned from the ORM is not exactly the same as in DB
# (floating point transformations). We need to give it some extra margin to match self.
@denormalized(
3
Source : get.py
with Apache License 2.0
from bcgov
with Apache License 2.0
from bcgov
def get_nearest_municipalities(self, instance):
index = 0
nearest_municipalities = list(instance.nearest_municipalities.all().values())
for municipality in nearest_municipalities:
nearest_municipalities[index]['municipality_name'] = Municipality.objects.get(
id=municipality['municipality_id_id']).name
community_queryset = Community.objects.filter(
municipality_id=municipality['municipality_id_id']).annotate(
count=F('census_subdivision__pop_total_2016'))
nearest_municipalities[index]['municipality_population'] = 0
if len(community_queryset):
nearest_municipalities[index][
'municipality_population'] = community_queryset.values()[0]['count']
index += 1
return nearest_municipalities
3
Source : kill_test_sub_process.py
with MIT License
from carrotquest
with MIT License
from carrotquest
def update(batch_size=500, test_time=60, period=1, **kwargs):
for iteration in range(int(test_time / period)):
updated = TestModel.objects.db_manager('test_db').\
filter(value__gte=iteration * batch_size, value__lt=(iteration + 1) * batch_size).\
annotate(valmod10=F('value') % 10).filter(valmod10=0).update(value=-1)
logger.debug('django-clickhouse: test updated %d records' % updated)
sleep(period)
def delete(batch_size=500, test_time=60, period=1, **kwargs):
3
Source : kill_test_sub_process.py
with MIT License
from carrotquest
with MIT License
from carrotquest
def delete(batch_size=500, test_time=60, period=1, **kwargs):
for iteration in range(int(test_time / period)):
deleted, _ = TestModel.objects.db_manager('test_db'). \
filter(value__gte=iteration * batch_size, value__lt=(iteration + 1) * batch_size). \
annotate(valmod10=F('value') % 10).filter(valmod10=1).delete()
logger.debug('django-clickhouse: test deleted %d records' % deleted)
sleep(period)
def sync(period=1, test_time=60, **kwargs):
3
Source : views.py
with MIT License
from cordx56
with MIT License
from cordx56
def get(self, request):
weekago = timezone.now() - datetime.timedelta(days=7)
query = TextGenHistory.objects.filter(gen_date__gt=weekago).filter(~Q(target_user=F('request_from')) | Q(request_from__isnull=True)).values('target_user').annotate(count=Count('target_user')).order_by('count').reverse()[:10]
result = []
for q in query:
user = User.objects.filter(id=q['target_user']).first()
result.append({ 'screen_name': user.screen_name, 'count': q['count'] })
return Response({ 'status': True, 'ranking': result })
3
Source : input_data_factories.py
with MIT License
from devind-team
with MIT License
from devind-team
def create_search_config(input_type: SearchConfigInputType) -> Union[str, models.F]:
"""Create a `SearchVector` or `SearchQuery` object config."""
return models.F(input_type.value) if input_type.is_field else input_type.value
def create_search_rank_weights(input_type: SearchRankWeightsInputType) -> List[float]:
3
Source : test_input_data_factories.py
with MIT License
from devind-team
with MIT License
from devind-team
def test_create_search_config(self) -> None:
"""Test the `create_search_config` function."""
string_input_type = SearchConfigInputType._meta.container({
'value': 'russian',
'is_field': False,
})
string_config = create_search_config(string_input_type)
self.assertEqual(string_input_type.value, string_config)
field_input_type = SearchConfigInputType._meta.container({
'value': 'russian',
'is_field': True,
})
field_config = create_search_config(field_input_type)
self.assertEqual(models.F('russian'), field_config)
def test_create_search_query(self) -> None:
3
Source : example.py
with MIT License
from doccano
with MIT License
from doccano
def get_queryset(self):
queryset = self.model.objects.filter(project=self.project)
if self.project.random_order:
# Todo: fix the algorithm.
random.seed(self.request.user.id)
value = random.randrange(2, 20)
queryset = queryset.annotate(sort_id=F("id") % value).order_by("sort_id", "id")
else:
queryset = queryset.order_by("created_at")
return queryset
def perform_create(self, serializer):
3
Source : 0012_auto_20210119_1308.py
with BSD 3-Clause "New" or "Revised" License
from druids
with BSD 3-Clause "New" or "Revised" License
from druids
def set_mobile_device_changed_at(apps, schema_editor):
MobileDevice = apps.get_model('auth_token', 'MobileDevice')
MobileDevice.objects.filter(last_login__isnull=True).update(changed_at=F('created_at'))
MobileDevice.objects.filter(last_login__isnull=False).update(changed_at=F('last_login'))
class Migration(migrations.Migration):
3
Source : views.py
with GNU Affero General Public License v3.0
from Dwarni
with GNU Affero General Public License v3.0
from Dwarni
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
ranking = AntSpecies \
.objects \
.filter(distribution__region__type='Country') \
.annotate(rank_entry_name=F('distribution__region__name')) \
.values('rank_entry_name') \
.annotate(total=Count('rank_entry_name')) \
.order_by('-total')[:self.num_entries]
context['ranking'] = ranking
context['max_total'] = ranking[0]['total']
context['heading'] = 'countries by number of ant species'
return context
def dictfetchall(cursor):
3
Source : views.py
with GNU Affero General Public License v3.0
from Dwarni
with GNU Affero General Public License v3.0
from Dwarni
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
ranking = AntSpecies \
.objects \
.filter(distribution__region__type='Country') \
.annotate(
rank_entry_name=F('name'),
total=Count('distribution__region__name')
) \
.values('rank_entry_name', 'total') \
.order_by('-total')[:self.num_entries]
context['ranking'] = ranking
context['max_total'] = ranking[0]['total']
context['heading'] = 'ant species by number of countries'
return context
class TopAntGeneraByNumberOfCountries(Ranking):
3
Source : views.py
with GNU Affero General Public License v3.0
from Dwarni
with GNU Affero General Public License v3.0
from Dwarni
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
ranking = Genus \
.objects \
.annotate(
rank_entry_name=F('name'),
total=Count('species')
) \
.values('rank_entry_name', 'total') \
.order_by('-total')[:self.num_entries]
context['ranking'] = ranking
context['max_total'] = ranking[0]['total']
context['heading'] = 'ant genera by number of species'
return context
class TopAuthorsByNumberOfAntSpecies(Ranking):
3
Source : views.py
with GNU Affero General Public License v3.0
from Dwarni
with GNU Affero General Public License v3.0
from Dwarni
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
ranking = AntSpecies \
.objects \
.annotate(rank_entry_name=F('author')) \
.values('rank_entry_name') \
.annotate(total=Count('rank_entry_name')) \
.order_by('-total')[:self.num_entries]
context['ranking'] = ranking
context['max_total'] = ranking[0]['total']
context['heading'] = 'authors by number of ant species'
return context
class AntSpeciesDetail(DetailView):
3
Source : views.py
with GNU Affero General Public License v3.0
from Dwarni
with GNU Affero General Public License v3.0
from Dwarni
def get(self, request, region, region2):
region_query = get_region_query(region)
region2_query = get_region_query(region2)
species_in_query = get_species_in_query(region2_query)
ants = (Distribution
.objects
.filter(region_query)
.exclude(species_in_query)
.order_by('species__name')
.values(name=F('species__name')))
return Response(ants)
class AntsByRegionCommonView(APIView):
3
Source : views.py
with GNU Affero General Public License v3.0
from Dwarni
with GNU Affero General Public License v3.0
from Dwarni
def get(self, request, region, region2):
region_query = get_region_query(region)
region2_query = get_region_query(region2)
species_in_query = get_species_in_query(region2_query)
ants = (Distribution
.objects
.filter(region_query, species_in_query)
.order_by('species__name')
.values(name=F('species__name')))
return Response(ants)
class AntsByGenusView(generics.ListAPIView):
3
Source : views.py
with GNU Affero General Public License v3.0
from Dwarni
with GNU Affero General Public License v3.0
from Dwarni
def add_top_species(self, query_set, context):
species = (query_set
.values(name=F('ant_species__name'))
.annotate(count=Count('name'))
.order_by('-count'))[:10]
context['top_species'] = species
context['top_species_max_reports'] = species.first()['count']
def add_top_countries(self, query_set, context):
3
Source : views.py
with GNU Affero General Public License v3.0
from Dwarni
with GNU Affero General Public License v3.0
from Dwarni
def add_top_countries(self, query_set, context):
countries = (query_set
.values(name=F('country__name'))
.annotate(count=Count('name'))
.order_by('-count'))[:10]
context['top_countries'] = countries
context['top_countries_max_reports'] = countries.first()['count']
3
Source : models.py
with Apache License 2.0
from dylanleigh
with Apache License 2.0
from dylanleigh
def sorted_prices(self):
'''
Return all the prices of this ingredient, annotated by
cents_per_kg, and sorted by it.
'''
# XXX: If both values are whole numbers, SQLite will silently assume
# integer division in an F(), possibly discarding a remainder of
# cents and producing erroneous results. Hence we need to
# multiply by 100 to ensure the cents are preserved if that
# happens.
Price = apps.get_model('products','Price')
prices = Price.objects.filter(ingredient=self).annotate(
cents_per_kg = F('price') * 100 / F('weight')
)
return prices.order_by('cents_per_kg')
@cached_property
3
Source : migrate_to_user_libraries.py
with GNU Affero General Public License v3.0
from ellisist
with GNU Affero General Public License v3.0
from ellisist
def set_fid(queryset, path, stdout):
model = queryset.model._meta.label
qs = queryset.filter(fid=None)
base_url = "{}{}".format(settings.FUNKWHALE_URL, path)
stdout.write(
"* Assigning federation ids to {} entries (path: {})".format(model, base_url)
)
new_fid = functions.Concat(Value(base_url), F("uuid"), output_field=CharField())
total = qs.update(fid=new_fid)
stdout.write(" * {} entries updated".format(total))
def update_shared_inbox_url(stdout):
3
Source : migrate_to_user_libraries.py
with GNU Affero General Public License v3.0
from ellisist
with GNU Affero General Public License v3.0
from ellisist
def generate_actor_urls(part, stdout):
field = "{}_url".format(part)
stdout.write("* Update {} for local actors...".format(field))
queryset = federation_models.Actor.objects.local().filter(**{field: None})
base_url = "{}/federation/actors/".format(settings.FUNKWHALE_URL)
new_field = functions.Concat(
Value(base_url),
F("preferred_username"),
Value("/{}".format(part)),
output_field=CharField(),
)
queryset.update(**{field: new_field})
def main(command, **kwargs):
3
Source : models.py
with GNU Affero General Public License v3.0
from ellisist
with GNU Affero General Public License v3.0
from ellisist
def remove(self, index):
existing = self.playlist_tracks.select_for_update()
self.save(update_fields=["modification_date"])
to_update = existing.filter(index__gt=index)
return to_update.update(index=models.F("index") - 1)
@transaction.atomic
3
Source : test_django_hashids.py
with MIT License
from ericls
with MIT License
from ericls
def test_can_select_as_integer():
from tests.test_app.models import TestModel
instance = TestModel.objects.create()
instance2 = TestModel.objects.create()
integer_ids = list(
TestModel.objects.annotate(
hid=ExpressionWrapper(F("hashid"), output_field=IntegerField())
).values_list("hid", flat=True)
)
assert set([instance.id, instance2.id]) == set(integer_ids)
@override_settings(DJANGO_HASHIDS_MIN_LENGTH=10)
3
Source : views.py
with MIT License
from etalab
with MIT License
from etalab
def get_queryset(self):
project = get_object_or_404(Project, pk=self.kwargs['project_id'])
queryset = project.documents
if project.randomize_document_order:
queryset = queryset.annotate(sort_id=F('id') % self.request.user.id).order_by('sort_id')
return queryset
def perform_create(self, serializer):
3
Source : views.py
with MIT License
from FalseG0d
with MIT License
from FalseG0d
def home(request):
Product.objects.update(price=F('price')*1.2)
products=Product.objects.all()
context={
'products':products,
}
return render(request,"index.html",context)
3
Source : scores.py
with GNU General Public License v3.0
from foonsun
with GNU General Public License v3.0
from foonsun
def calculate_scores(self):
self.logger.info("Calculating product scores")
total_weight = float(sum(self.weights.values()))
weighted_fields = [
self.weights[name] * F(name) for name in self.weights.keys()]
ProductRecord.objects.update(
score=sum(weighted_fields) / total_weight)
3
Source : receivers.py
with GNU General Public License v3.0
from foonsun
with GNU General Public License v3.0
from foonsun
def track_voucher_addition(basket, voucher, **kwargs):
voucher.num_basket_additions += 1
voucher.__class__._default_manager.filter(pk=voucher.pk).update(
num_basket_additions=F('num_basket_additions') + 1,
)
def track_voucher_removal(basket, voucher, **kwargs):
See More Examples