django.db.models.F

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.

173 Examples 7

Example 1

Project: commcare-hq Source File: invoicing.py
Function: get_subscriptions
    def _get_subscriptions(self):
        subscriptions = Subscription.objects.filter(
            subscriber=self.subscriber, date_start__lte=self.date_end
        ).filter(
            Q(date_end=None) | Q(date_end__gt=self.date_start)
        ).filter(
            Q(date_end=None) | Q(date_end__gt=F('date_start'))
        ).order_by('date_start', 'date_end').all()
        return list(subscriptions)

Example 2

Project: django-machina Source File: handler.py
    def _update_parent_forum_tracks(self, forum, user):
        for forum in forum.get_ancestors(ascending=True):
            # If no other topics are unread inside the considered forum, the latter should also
            # be marked as read.
            unread_topics = forum.topics.filter(
                Q(tracks__user=user, tracks__mark_time__lt=F('last_post_on')) |
                Q(forum__tracks__user=user, forum__tracks__mark_time__lt=F('last_post_on'),
                  tracks__isnull=True))
            if unread_topics.exists():
                break

            # The topics that are marked as read inside the forum for the given user
            # wil be deleted while the forum track associated with the user must be
            # created or updated.
            TopicReadTrack.objects.filter(topic__forum=forum, user=user).delete()
            forum_track, _ = ForumReadTrack.objects.get_or_create(forum=forum, user=user)
            forum_track.save()

Example 3

Project: votes Source File: managers.py
Function: up
    @instance_required
    def up(self, user, vote):
        with transaction.atomic():
            if self.through.objects.filter(user=user, content_object=self.instance).exists():
                c_type = ContentType.objects.get_for_model(self.instance)
                vote_obj = self.through.objects.get(user=user, object_id=self.instance.id, content_type=c_type)
                vote_obj.vote = vote
                vote_obj.save()
                self.instance.save()
            else:
                self.through(user=user, content_object=self.instance, vote=vote).save()
                if self.extra_field:
                    setattr(self.instance, self.extra_field, F(self.extra_field)+1)
                    self.instance.save()

Example 4

Project: doc-versions Source File: fixdocuments_remove_phantoms.py
Function: fix_model
def fix_model(model):
    mn = model.__name__
    info('fixing model : ' + mn)

    c = model.objects.filter(docuement_start__gte=F('docuement_end')).count()
    if c:
        model.objects.filter(docuement_start__gte=F('docuement_end')).delete()
        warning(mn + ': %d phantom docuement(s) removed' % c)
    else:
        info(mn + ': no phantom docuements found')

Example 5

Project: pootle Source File: models.py
Function: save
    def save(self, *args, **kwargs):
        # copy current user rate
        self.rate = self.user.rate
        self.review_rate = self.user.review_rate
        self.score_delta = self.get_score_delta()
        translated = self.get_paid_wordcounts()[0]
        self.translated_wordcount = translated

        super(ScoreLog, self).save(*args, **kwargs)

        User = get_user_model()
        User.objects.filter(id=self.user.id).update(
            score=F('score') + self.score_delta
        )
        self.log()

Example 6

Project: django-treebeard Source File: al_tree.py
    @classmethod
    def _make_hole_in_db(cls, min, target_node):
        qset = get_result_class(cls).objects.filter(sib_order__gte=min)
        if target_node.is_root():
            qset = qset.filter(parent__isnull=True)
        else:
            qset = qset.filter(parent=target_node.parent)
        qset.update(sib_order=models.F('sib_order') + 1)

Example 7

Project: django-oscar Source File: scores.py
Function: calculate_scores
    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)

Example 8

Project: SmartElect Source File: sending.py
def send_messages(batch, num_to_send=250, map_=map):
    """
    Send ``num_to_send`` oldest messages from the specified ``batch``. If none
    left to send, update status to COMPLETED. Return the number of messages sent.

    If supplied, ``map_`` must be a method that behaves like the ``map``
    build-in. A parallelized version, e.g., ``multiprocessing.Pool.map``,
    can be used to improve message sending throughput.
    """
    message_pks = batch.messages.unsent().values_list('id', flat=True)[:num_to_send]
    num_sent = sum(map_(send_message_by_id, message_pks))
    errors = len(message_pks) - num_sent
    # check to see if we sent all the messages yet
    if not batch.messages.unsent().exists():
        # no messages, Batch is complete
        Batch.objects.filter(pk=batch.pk).update(status=Batch.COMPLETED)
    if errors:
        Batch.objects.filter(pk=batch.pk).update(errors=F('errors')+errors)
    return num_sent

Example 9

Project: vcs-translator Source File: utils.py
    def handle_step(self, command, step, *args, **kwargs):
        try:
            res = step(*args, **kwargs)
            if res is None:
                raise CantHandleYet
        except CantHandleYet:
            f, _ = FailedTranslation.objects.get_or_create(
                source=self.source,
                target=self.target,
                command=command,
            )
            FailedTranslation.objects.filter(pk=f.pk).update(count=F("count") + 1)
            return TranslationFailure("We can't handle this yet, we've let the monkeys^W programmers in the back room know."), False
        except CantHandle:
            return TranslationFailure("This VCS doesn't support this operation"), False
        return res, True

Example 10

Project: volontulo Source File: models.py
Function: publish
    def publish(self):
        u"""Publish offer."""
        self.offer_status = 'published'
        Offer.objects.all().update(weight=F('weight') + 1)
        self.weight = 0
        self.save()
        return self

Example 11

Project: django-mysql Source File: test_functions.py
    def test_regex_substr_field(self):
        Alphabet.objects.create(d='This is the string', e=r'\bis\b')
        qs = (
            Alphabet.objects.annotate(substr=RegexpSubstr('d', F('e')))
                            .filter(substr__gt='')
                            .values_list('substr', flat=True)
        )
        substr = qs[0]
        assert substr == 'is'

Example 12

Project: django-badgify Source File: signals.py
@receiver(pre_delete, sender=Award, dispatch_uid='badgify.award.pre_delete.decrement_badge_users_count')
def decrement_badge_users_count(sender, instance, **kwargs):
    from django.db.models import F
    from .settings import AUTO_DENORMALIZE

    if AUTO_DENORMALIZE and instance.badge.users_count >= 1:
        instance.badge.users_count = F('users_count') - 1
        instance.badge.save()

Example 13

Project: syndicate Source File: sync_volume.py
Function: fetch_pending
    def fetch_pending(self):
        try:
            ret = Volume.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
            return ret
        except Exception, e:
            traceback.print_exc()
            return None

Example 14

Project: iCQA Source File: user.py
Function: cancel_action
    def cancel_action(self):
        award = self.award
        badge = award.badge
        badge.awarded_count = F('awarded_count') - 1
        badge.save()
        award.delete()

Example 15

Project: oioioi Source File: miniprofile.py
@miniprofile_tab(_("Problems"), 200)
def friend_problems_tab(request):
    friends = UserFriends(request.user).friends

    rfps = UserResultForProblem.objects.filter(
        user__in=friends,
        submission_report__scorereport__score=
        F('submission_report__scorereport__max_score'),
        submission_report__submission__problem_instance__contest__isnull=True
    ).select_related('submission_report__submission'
                     '__problem_instance__problem')

    submissions = [rfp.submission_report.submission
                   for rfp in rfps[:MAX_SUGGESTIONS_FROM_FRIENDS]]

    return render_to_string('gamification/miniprofile/tabs/problems.html',
            {'submissions': submissions})

Example 16

Project: django-money Source File: test_models.py
def test_allow_expression_nodes_without_money():
    """Allow querying on expression nodes that are not Money"""
    desc = 'hundred'
    ModelWithNonMoneyField.objects.create(money=Money(100.0), desc=desc)
    instance = ModelWithNonMoneyField.objects.filter(desc=F('desc')).get()
    assert instance.desc == desc

Example 17

Project: django-natural-query Source File: query.py
Function: in_values
    def in_values(self, *args):
        args = list(args)
        for i, arg in enumerate(args):
            if isinstance(arg, NaturalQueryDescriptor):
                args[i] = F(arg.name)
        args = tuple(args)
        return self._transform_operator_to_query_object('in', args)

Example 18

Project: site Source File: api.py
def api_user_info(request, user):
    profile = get_object_or_404(Profile, user__username=user)
    submissions = list(Submission.objects.filter(case_points=F('case_total'), user=profile, problem__is_public=True)
                       .values('problem').distinct().values_list('problem__code', flat=True))
    return JsonResponse({
        'display_name': profile.name,
        'points': profile.points,
        'rank': profile.display_rank,
        'solved_problems': submissions,
        'organizations': list(profile.organizations.values_list('key', flat=True)),
    })

Example 19

Project: django-dirtyfields Source File: test_non_regression.py
@pytest.mark.django_db
def test_expressions_not_taken_into_account_for_dirty_check():
    # Non regression test case for bug:
    # https://github.com/romgar/django-dirtyfields/issues/39
    from django.db.models import F
    tm = TestExpressionModel.objects.create()
    tm.counter = F('counter') + 1

    # This save() was raising a ValidationError: [u"'F(counter) + Value(1)' value must be an integer."]
    # caused by a call to_python() on an expression node
    tm.save()

Example 20

Project: django-blog-zinnia Source File: signals.py
def count_trackbacks_handler(sender, **kwargs):
    """
    Update Entry.trackback_count when a trackback was posted.
    """
    entry = kwargs['entry']
    entry.trackback_count = F('trackback_count') + 1
    entry.save(update_fields=['trackback_count'])

Example 21

Project: wagtail Source File: models.py
    def add_hit(self, date=None):
        if date is None:
            date = timezone.now().date()
        daily_hits, created = QueryDailyHits.objects.get_or_create(query=self, date=date)
        daily_hits.hits = models.F('hits') + 1
        daily_hits.save()

Example 22

Project: pootle Source File: resources.py
    @cached_property
    def pootle_changed(self):
        """StoreFS queryset of tracked resources where the Store has changed
        since it was last synced.
        """
        return (
            self.synced.exclude(store_id__isnull=True)
                       .exclude(store__obsolete=True)
                       .annotate(max_revision=Max("store__unit__revision"))
                       .exclude(last_sync_revision=F("max_revision")))

Example 23

Project: readthedocs.org Source File: models.py
    def incr(self, type, project=None):
        """Add to the number of times this action has been performed, stored in the DB"""
        assert type in IMPRESSION_TYPES
        day = get_ad_day()
        if project:
            impression, _ = self.project_impressions.get_or_create(date=day, project=project)
        else:
            impression, _ = self.impressions.get_or_create(date=day)

        setattr(impression, type, models.F(type) + 1)
        impression.save()

Example 24

Project: django-badgify Source File: signals.py
@receiver(post_save, sender=Award, dispatch_uid='badgify.award.post_save.increment_badge_users_count')
def increment_badge_users_count(sender, instance, created, **kwargs):
    from django.db.models import F
    from .settings import AUTO_DENORMALIZE

    if created and AUTO_DENORMALIZE:
        instance.badge.users_count = F('users_count') + 1
        instance.badge.save()

Example 25

Project: datacommons Source File: match_lobbyist_bundlers__individuals.py
    def __init__(self, *args, **kwargs):
        super(Command, self).__init__(*args, **kwargs)
        self.subject = LobbyistBundle.objects.exclude(name=F('employer')).extra(where=['name not in (select name from assoc_bundler_matches_manual)']).order_by('name')
        self.subject_name_attr = 'name'
        self.subject_id_type = 'integer'

        self.match = Entity.objects.filter(type='individual').extra(where=[
            'id in (select entity_id from assoc_lobbying_lobbyist)',
        ])
        self.match_table_prefix = 'bundler_indiv'

Example 26

Project: django-modeltranslation Source File: manager.py
Function: rewrite_f
    def _rewrite_f(self, q):
        """
        Rewrite field names inside F call.
        """
        if isinstance(q, models.F):
            q.name = rewrite_lookup_key(self.model, q.name)
            return q
        if isinstance(q, Node):
            q.children = map(self._rewrite_f, q.children)
        return q

Example 27

Project: django-ordered-model Source File: models.py
Function: delete
    def delete(self, *args, **kwargs):
        qs = self.get_ordering_queryset()
        update_kwargs = {self.order_field_name: F(self.order_field_name) - 1}
        extra = kwargs.pop('extra_update', None)
        if extra:
            update_kwargs.update(extra) 
        qs.filter(**{self.order_field_name + '__gt': getattr(self, self.order_field_name)})\
          .update(**update_kwargs)
        super(OrderedModelBase, self).delete(*args, **kwargs)

Example 28

Project: amy Source File: views.py
    @list_route(methods=['GET'])
    def instructor_num_taught(self, request, format=None):
        badges = Badge.objects.instructor_badges()
        persons = Person.objects.filter(badges__in=badges).annotate(
            num_taught=Count(
                Case(
                    When(
                        task__role__name='instructor',
                        then=F('task'),
                    ),
                ),
                distinct=True
            )
        ).order_by('-num_taught')
        serializer = InstructorNumTaughtSerializer(
            persons, many=True, context=dict(request=request))
        return Response(serializer.data)

Example 29

Project: django-mysql Source File: test_handler.py
    def test_read_where_filter_f_expression(self):
        qs = Author.objects.filter(name=F('name'))

        with qs.handler() as handler:
            handler_all = list(handler.read(limit=100))

        assert len(handler_all) == 2

Example 30

Project: tai5-uan5_gian5-gi2_phing5-tai5 Source File: 項目模型.py
    @classmethod
    def 這句講了按怎(cls, 平臺項目編號, decision):
        if decision == '按呢講好':
            return (
                平臺項目表.objects
                .filter(pk=平臺項目編號)
                .update(按呢講好=F('按呢講好') + 1)
            )
        elif decision == '按呢無好':
            return (
                平臺項目表.objects
                .filter(pk=平臺項目編號)
                .update(按呢無好=F('按呢無好') + 1)
            )
        else:
            raise ValueError('decision傳毋著')

Example 31

Project: votainteligente-portal-electoral Source File: models.py
Function: get_query_set
    def get_queryset(self):
        qs = super(RankingManager, self).get_queryset()
        qs = qs.annotate(possible_answers=Count(F('elections__categories__topics'), distinct=True))
        qs = qs.annotate(num_answers=Count('taken_positions', distinct=True))
        qs = qs.annotate(naranja_completeness=ExpressionWrapper((F('num_answers') * 1.0 / F('possible_answers') * 1.0) * 100,
                                                                output_field=FloatField()))

        qs = qs.annotate(num_proposals=Count(F('elections__area__proposals'), distinct=True))
        qs = qs.annotate(num_commitments=Count(F('commitments'), distinct=True))
        qs = qs.annotate(commitmenness=ExpressionWrapper((F('num_commitments') * 1.0 / F('num_proposals') * 1.0) * 100,
                                                                output_field=FloatField()))

        # This can be a bit tricky
        # and it is the sum of the percentage of completeness of 1/2 naranja and the commitmenness
        qs = qs.annotate(participation_index=ExpressionWrapper(F('naranja_completeness') + F('commitmenness'),
                                                                output_field=FloatField()))
        qs = qs.order_by('-has_won', '-participation_index')
        return qs

Example 32

Project: syndicate Source File: sync_volume.py
Function: fetch_deleted
    def fetch_deleted(self):
        try:
            ret = Volume.deleted_objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
            return ret
        except Exception, e:
            traceback.print_exc()
            return None

Example 33

Project: decode-Django Source File: tests.py
    def test_ticket_18375_chained_filters(self):
        # Test that F() expressions do not reuse joins from previous filter.
        qs = Employee.objects.filter(
            company_ceo_set__num_employees=F('pk')
        ).filter(
            company_ceo_set__num_employees=F('company_ceo_set__num_employees')
        )
        self.assertEqual(str(qs.query).count('JOIN'), 2)

Example 34

Project: rocket-league-replays Source File: models.py
Function: goals
    @cached_property
    def goals(self):
        if not self.replays.count():
            return 0
        return self.replays.aggregate(
            num_goals=models.Sum(models.F('team_0_score') + models.F('team_1_score'))
        )['num_goals']

Example 35

Project: django-bitfield Source File: admin.py
Function: queryset
    def queryset(self, request, queryset):
        filter = dict((p, bitor(F(p), v)) for p, v in six.iteritems(self.used_parameters))
        try:
            return queryset.filter(**filter)
        except ValidationError as e:
            raise IncorrectLookupParameters(e)

Example 36

Project: tendenci Source File: views.py
Function: get_query_set
    def get_queryset(self):
        if not perms.may_view_topic(self.request.user, self.topic):
            raise PermissionDenied
        if self.request.user.is_authenticated() or not defaults.PYBB_ANONYMOUS_VIEWS_CACHE_BUFFER:
            Topic.objects.filter(id=self.topic.id).update(views=F('views') + 1)
        else:
            cache_key = util.build_cache_key('anonymous_topic_views', topic_id=self.topic.id)
            cache.add(cache_key, 0)
            if cache.incr(cache_key) % defaults.PYBB_ANONYMOUS_VIEWS_CACHE_BUFFER == 0:
                Topic.objects.filter(id=self.topic.id).update(views=F('views') +
                                                                defaults.PYBB_ANONYMOUS_VIEWS_CACHE_BUFFER)
                cache.set(cache_key, 0)
        qs = self.topic.posts.all().select_related('user')
        if defaults.PYBB_PROFILE_RELATED_NAME:
            qs = qs.select_related('user__%s' % defaults.PYBB_PROFILE_RELATED_NAME)
        if not perms.may_moderate_topic(self.request.user, self.topic):
            qs = perms.filter_posts(self.request.user, qs)
        return qs

Example 37

Project: django-oscar Source File: receivers.py
def _record_user_order(user, order):
    try:
        record = UserRecord.objects.filter(user=user)
        affected = record.update(
            num_orders=F('num_orders') + 1,
            num_order_lines=F('num_order_lines') + order.num_lines,
            num_order_items=F('num_order_items') + order.num_items,
            total_spent=F('total_spent') + order.total_incl_tax,
            date_last_order=order.date_placed)
        if not affected:
            UserRecord.objects.create(
                user=user, num_orders=1, num_order_lines=order.num_lines,
                num_order_items=order.num_items,
                total_spent=order.total_incl_tax,
                date_last_order=order.date_placed)
    except IntegrityError:
        logger.error(
            "IntegrityError in analytics when recording a user order.")

Example 38

Project: oioioi Source File: showbrokensolutions.py
    def get_problems_without_correct_modelsolution(self, username=None):
        if username is not None:
            problems = Problem.objects.filter(author__username=username)
        else:
            problems = Problem.objects.all()
        bad_problems = []
        for problem in problems:
            correct_model_submissions = ModelProgramSubmission.objects.filter(
                score=F('submissionreport__scorereport__max_score'),
                model_solution__problem=problem).order_by('id')
            if not correct_model_submissions:
                bad_problems.append(problem)
        return bad_problems

Example 39

Project: patchwork Source File: utils.py
def do_expiry():
    # expire any pending confirmations
    q = (Q(date__lt=datetime.datetime.now() - EmailConfirmation.validity) |
         Q(active=False))
    EmailConfirmation.objects.filter(q).delete()

    # expire inactive users with no pending confirmation
    pending_confs = EmailConfirmation.objects.values('user')
    users = User.objects.filter(is_active=False,
                                last_login=F('date_joined')).exclude(
                                    id__in=pending_confs)

    # delete users
    users.delete()

Example 40

Project: django-natural-query Source File: query.py
Function: between
    def between(self, low, high):
        if isinstance(low, NaturalQueryDescriptor):
            low = F(low.name)
        if isinstance(high, NaturalQueryDescriptor):
            high = F(high.name)
        return self._transform_operator_to_query_object('range', (low, high))

Example 41

Project: site Source File: submission.py
Function: get_object
    def get_object(self, queryset=None):
        submission = super(SubmissionDetailBase, self).get_object(queryset)
        profile = self.request.user.profile

        if (not self.request.user.has_perm('judge.view_all_submission') and submission.user_id != profile.id and
                not submission.problem.authors.filter(id=profile.id).exists() and
                not (submission.problem.is_public and
                     Submission.objects.filter(user_id=profile.id, result='AC',
                                               problem__code=submission.problem.code,
                                               points=F('problem__points')).exists())):
            raise PermissionDenied()
        return submission

Example 42

Project: classic.rhizome.org Source File: models.py
def delete_hit_count_callback(sender, instance, 
        save_hitcount=False, **kwargs):
    '''
    Custom callback for the Hit.delete() method.

    Hit.delete(): removes the hit from the associated HitCount object.
    Hit.delete(save_hitcount=True): preserves the hit for the associated
        HitCount object.
    '''
    if not save_hitcount:
        instance.hitcount.hits = F('hits') - 1
        instance.hitcount.save()

Example 43

Project: django-blog-zinnia Source File: signals.py
def count_pingbacks_handler(sender, **kwargs):
    """
    Update Entry.pingback_count when a pingback was posted.
    """
    entry = kwargs['entry']
    entry.pingback_count = F('pingback_count') + 1
    entry.save(update_fields=['pingback_count'])

Example 44

Project: votes Source File: managers.py
Function: down
    @instance_required
    def down(self, user):
        with transaction.atomic():
            self.through.objects.filter(user=user, content_object=self.instance).delete()
            if self.extra_field:
                setattr(self.instance, self.extra_field, F(self.extra_field)-1)
                self.instance.save()

Example 45

Project: mezzanine Source File: models.py
    def delete(self, *args, **kwargs):
        """
        Update the ordering values for siblings.
        """
        lookup = self.with_respect_to()
        lookup["_order__gte"] = self._order
        concrete_model = base_concrete_model(Orderable, self)
        after = concrete_model.objects.filter(**lookup)
        after.update(_order=models.F("_order") - 1)
        super(Orderable, self).delete(*args, **kwargs)

Example 46

Project: django-pageviews Source File: middleware.py
Function: process_request
    def process_request(self, request, *args, **kwargs):
        hit, hit_created = HitCount.objects.get_or_create(url=request.path)
        hit.hits = F('hits') + 1
        hit.save()

        return None

Example 47

Project: classic.rhizome.org Source File: models.py
Function: save
    def save(self, *args, **kwargs):
        '''
        The first time the object is created and saved, we increment 
        the associated HitCount object by one.  The opposite applies
        if the Hit is deleted.
        '''
        if not self.created:
            self.hitcount.hits = F('hits') + 1
            self.hitcount.save()
            self.created = datetime.datetime.utcnow()

        super(Hit, self).save(*args, **kwargs)

Example 48

Project: SchoolIdolAPI Source File: utils.py
def validate_vote(choice, session, contest):
    if choice == 'left':
        vote = session.left
        negative_vote = session.right
    elif choice == 'right':
        vote = session.right
        negative_vote = session.left
    contest_models.Vote.objects.filter(pk=vote.id).update(counter=F('counter') + 1)
    contest_models.Vote.objects.filter(pk=negative_vote.id).update(negative_counter=F('negative_counter') + 1)
    session.delete()
    return

Example 49

Project: django-cacheops Source File: tests.py
    def test_expressions_save(self):
        # Check saving F
        extra = Extra.objects.get(pk=1)
        extra.tag = F('tag')
        extra.save()

        # Check saving ExressionNode
        Extra.objects.create(post_id=3, tag=7)
        extra = Extra.objects.get(pk=3)
        extra.tag = F('tag') + 1
        extra.save()

Example 50

Project: django-synchro Source File: tests.py
Function: wait
    def wait(self):
        """
        Since tests are run too fast, we need to wait for a moment, so that some ChangeLog objects
        could be considered "old" and not synchronized again.
        Waiting one second every time this method is called would lengthen tests - so instead we
        simulate time shift.
        """
        ChangeLog.objects.update(date=F('date') - datetime.timedelta(seconds=1))
        ChangeLog.objects.db_manager(REMOTE).update(date=F('date') - datetime.timedelta(seconds=1))
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4