Пример #1
0
 def test_expressions(self):
     authors = Author.objects.annotate(
         name_part=Right('name', Value(3), output_field=CharField()))
     self.assertQuerysetEqual(authors.order_by('name'), ['ith', 'nda'],
                              lambda a: a.name_part)
Пример #2
0
    def get_queryset(self):
        config = PartnershipConfiguration.get_configuration()
        academic_year = config.get_current_academic_year_for_api()
        self.academic_year = academic_year
        academic_year_repr = Concat(
            Cast(F('academic_year__year'), models.CharField()),
            Value('-'),
            Right(
                Cast(F('academic_year__year') + 1,
                     output_field=models.CharField()), 2),
        )

        return (PartnershipPartnerRelation.objects.filter_for_api(
            academic_year
        ).annotate_partner_address(
            'country__continent__name',
            'country__iso_code',
            'country__name',
            'country_id',
            'city',
            'location',
        ).select_related(
            'entity__partnerentity',
            'entity__organization',
        ).prefetch_related(
            Prefetch(
                'partnership',
                queryset=Partnership.objects.add_acronyms().select_related(
                    'subtype',
                    'supervisor',
                ).prefetch_related(
                    'contacts', 'missions',
                    Prefetch(
                        'partner_entities',
                        queryset=EntityProxy.objects.with_partner_info(),
                    ))),
            Prefetch(
                'partnership__medias',
                queryset=Media.objects.select_related('type').filter(
                    is_visible_in_portal=True),
            ),
            Prefetch(
                'entity__organization__partner',
                queryset=(Partner.objects.annotate_address(
                    'country__iso_code',
                    'country__name',
                    'city',
                ).annotate_website(
                ).select_related('organization').prefetch_related(
                    Prefetch(
                        'medias',
                        queryset=Media.objects.filter(
                            is_visible_in_portal=True).select_related('type')),
                ).annotate_partnerships_count()),
                to_attr='partner_prefetched',
            ),
            Prefetch('partnership__ucl_entity',
                     queryset=EntityProxy.objects.select_related(
                         'uclmanagement_entity__academic_responsible',
                         'uclmanagement_entity__administrative_responsible',
                         'uclmanagement_entity__contact_out_person',
                         'uclmanagement_entity__contact_in_person',
                     ).with_title().with_acronym()),
            Prefetch(
                'partnership__years',
                queryset=(PartnershipYear.objects.select_related(
                    'academic_year',
                    'funding_source',
                    'funding_program',
                    'funding_type',
                ).prefetch_related(
                    Prefetch('entities',
                             queryset=EntityProxy.objects.with_title(
                             ).with_acronym()),
                    'education_fields',
                    'education_levels',
                    'offers',
                ).filter(academic_year=academic_year)),
                to_attr='current_year_for_api',
            ),
            Prefetch(
                'partnership__agreements',
                queryset=(PartnershipAgreement.objects.select_related(
                    'media', 'end_academic_year').filter(
                        status=AgreementStatus.VALIDATED.name).filter(
                            start_academic_year__year__lte=academic_year.year,
                            end_academic_year__year__gte=academic_year.year,
                        )),
                to_attr='valid_current_agreements',
            ),
        ).annotate(
            validity_end_year=Subquery(
                AcademicYear.objects.filter(
                    partnership_agreements_end__partnership=OuterRef(
                        'partnership_id'),
                    partnership_agreements_end__status=AgreementStatus.
                    VALIDATED.name).order_by('-end_date').values('year')[:1]),
            agreement_start=Subquery(
                PartnershipAgreement.objects.filter(
                    partnership=OuterRef('partnership_id'),
                    start_date__lte=Now(),
                    end_date__gte=Now(),
                ).order_by('-end_date').values('start_date')[:1]),
            start_year=Subquery(
                PartnershipYear.objects.filter(
                    partnership=OuterRef('partnership_id'), ).annotate(
                        name=academic_year_repr).order_by(
                            'academic_year').values('name')[:1]),
            end_year=Subquery(
                PartnershipYear.objects.filter(
                    partnership=OuterRef('partnership_id'), ).annotate(
                        name=academic_year_repr).order_by(
                            '-academic_year').values('name')[:1]),
            agreement_end=Subquery(
                PartnershipAgreement.objects.filter(
                    partnership=OuterRef('partnership_id'),
                    start_date__lte=Now(),
                    end_date__gte=Now(),
                ).order_by('-end_date').values('end_date')[:1]),
        ).annotate(
            validity_years=Concat(Value(academic_year.year),
                                  Value('-'),
                                  F('validity_end_year') + 1,
                                  output_field=models.CharField()),
            agreement_status=Subquery(
                PartnershipAgreement.objects.filter(
                    partnership=OuterRef('partnership_id'),
                    start_academic_year__year__lte=academic_year.year,
                    end_academic_year__year__gte=academic_year.year,
                ).order_by('-end_academic_year__year').values('status')[:1]),
            funding_name=Subquery(
                Financing.objects.filter(
                    academic_year=academic_year,
                    countries=OuterRef('country_id'),
                ).values('type__name')[:1]),
            funding_url=Subquery(
                Financing.objects.filter(
                    academic_year=academic_year,
                    countries=OuterRef('country_id'),
                ).values('type__url')[:1]),
        ).distinct('pk').order_by('pk'))
Пример #3
0
 def test_invalid_length(self):
     with self.assertRaisesMessage(ValueError,
                                   "'length' must be greater than 0"):
         Author.objects.annotate(raises=Right('name', 0))
Пример #4
0
 def test_expressions(self):
     authors = Author.objects.annotate(
         name_part=Right("name", Value(3, output_field=IntegerField())))
     self.assertQuerysetEqual(authors.order_by("name"), ["ith", "nda"],
                              lambda a: a.name_part)
Пример #5
0
    def post(self, request):
        for field in ["name", "project"]:
            if (field not in request.data):
                return Response(
                    {'error': f'request is missing {field}'},
                    status=status.HTTP_400_BAD_REQUEST,
                )

        try:
            project = Project.objects.get(
                owner=request.user,
                name=request.data['project'],
                is_shared=False,
            )
        except Exception:
            return Response(
                {'error': 'invalid project'},
                status=status.HTTP_400_BAD_REQUEST,
            )

        try:
            media_path = get_valid_media_path(
                project.name,
                request.user.username,
                request.data['name'],
                is_directory=request.data['directory'],
            )
        except Exception:
            return Response(
                {'error': 'invalid filename'},
                status=status.HTTP_400_BAD_REQUEST,
            )

        name = newName = request.data['name']
        if 'newName' in request.data:
            try:
                new_path = get_valid_media_path(
                    project.name,
                    request.user.username,
                    request.data['newName'],
                )
            except Exception:
                return Response(
                    {'error': 'invalid new filename'},
                    status=status.HTTP_400_BAD_REQUEST,
                )
            else:
                newName = request.data['newName']

        if request.data['directory']:
            if 'newName' in request.data:
                os.rename(
                    os.path.join(settings.MEDIA_ROOT, media_path),
                    os.path.join(settings.MEDIA_ROOT, new_path),
                )
                Module.objects.filter(source__startswith=media_path).update(
                    source=Concat(
                        Value(new_path),
                        Right(
                            'source',
                            Length('source') - len(media_path)
                        )
                    )
                )
                return Response(request.data)
            else:
                os.mkdir(os.path.join(settings.MEDIA_ROOT, media_path))
                return Response(request.data)
        else:
            if 'code' in request.data:
                defaults = {
                    'time': timezone.now(),
                    'source': ContentFile(
                        request.data['code'],
                        name=newName,
                    ),
                }
                module, created = Module.objects.update_or_create(
                    owner=request.user,
                    project=project,
                    source=media_path,
                    defaults=defaults,
                )
            else:
                module = Module.objects.get(
                    owner=request.user,
                    project=project,
                    source=media_path,
                )
                module.source.name = new_path
                module.save()
                os.rename(
                    os.path.join(settings.MEDIA_ROOT, media_path),
                    os.path.join(settings.MEDIA_ROOT, new_path),
                )

            profile = Profile.objects.get(user=request.user)
            profile.last_module = module
            if 'scene' in request.data:
                profile.last_scene = request.data['scene']
            profile.last_project = project
            profile.save()

            module_serializer = SaveModuleSerializer(module)
            return Response(module_serializer.data)
Пример #6
0
def update_ref_counter(ref):
    """ Увеличение счетчика привлеченных пользователей на 1 для пользователя с указанным ref """
    Users.objects.annotate(email_md5=MD5('email')).annotate(
        ref_value=Right('email_md5', 8)).filter(
            ref_value=ref).values('ref').update(ref=F('ref') + 1)
Пример #7
0
def tag(request, tag_name):
    if request.method == "PUT":
        if 'new_name' in request.data and 'books' in request.data:
            new_name = request.data['new_name']
            new_books = request.data['books']
            request_user = User.objects.get(auth_token__key=request.auth)

            # find all occurrences of the provided tag name in the database
            matching_tags = BookTag.objects.filter(tag_name=tag_name,
                                                   user=request_user)
            if matching_tags.count() > 0:
                if len(new_books) > 0:
                    updated_tag = {"tag_name": new_name, "books": []}

                    for book_id in new_books:
                        matching_books = Book.objects.filter(id=book_id)
                        # if there's a matching book
                        if matching_books.count() > 0:
                            matching_book = matching_books[0]
                            matching_booktags = BookTag.objects.filter(
                                tag_name=tag_name,
                                user=request_user,
                                book=matching_book)
                            # if there's an existing booktag for it
                            if matching_booktags.count() > 0:
                                matching_booktag = matching_booktags[0]
                                matching_booktag.tag_name = new_name
                                matching_booktag.save()
                                updated_tag["books"].append(matching_book.id)
                            # if there isn't an existing booktag
                            else:
                                new_booktag = BookTag.objects.create(
                                    tag_name=new_name,
                                    user=request_user,
                                    book=matching_book)
                                updated_tag["books"].append(matching_book.id)
                        # if there isn't a matching book
                        else:
                            error_message = {
                                "error":
                                "Could not find book with ID: %s" % (book_id)
                            }
                            return Response(error_message,
                                            status=status.HTTP_400_BAD_REQUEST)

                    for matching_tag in matching_tags:
                        # if that tag's book id is not also in new_books
                        if matching_tag.book.id not in new_books:
                            matching_tag.delete()

                    # calculate prefix form
                    new_prefix = new_name + "__"
                    old_prefix = tag_name + "__"
                    old_prefix_length = len(old_prefix)
                    # update all tags with matching prefixes
                    BookTag.objects.filter(
                        tag_name__startswith=old_prefix,
                        user=request_user).update(tag_name=Concat(
                            Value(new_prefix),
                            Right(
                                F('tag_name'),
                                Length(F('tag_name')) -
                                Value(old_prefix_length))))

                    # add wrapper
                    json = {"tags": [updated_tag]}
                    return Response(json, status=status.HTTP_200_OK)

                # if new book list is empty, delete the tag instances
                else:
                    # serialize tags to be deleted
                    serializer = BookTagSerializer(matching_tags, many=True)
                    json = {"tags": serializer.data}
                    for tag in matching_tags:
                        tag.delete()
                    return Response(json, status=status.HTTP_200_OK)
            else:
                error_message = {
                    "error": "No tags match the name '%s'" % (tag_name)
                }
                return Response(error_message,
                                status=status.HTTP_400_BAD_REQUEST)
        else:
            error_message = {
                "error": "new name or list of books was not provided"
            }
            return Response(error_message, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == "DELETE":
        request_user = User.objects.get(auth_token__key=request.auth)

        # find all occurrences of the provided tag name in the database
        matching_tags = BookTag.objects.filter(tag_name=tag_name,
                                               user=request_user)

        if matching_tags.count() > 0:
            # serialize tags to be deleted
            serializer = BookTagSerializer(matching_tags, many=True)
            json = {"tags": serializer.data}

            # for each matching tag, delete that tag
            for tag in matching_tags:
                tag.delete()

            return Response(json, status=status.HTTP_200_OK)
        else:
            error_message = {
                "error":
                "Could not find any tags matching the name '%s'" % (tag_name)
            }
            return Response(error_message, status=status.HTTP_400_BAD_REQUEST)