Giter Club home page Giter Club logo

django-mongoengine-filter's Introduction

django-mongoengine-filter

django-mongoengine-filter is a reusable Django application for allowing users to filter mongoengine querysets dynamically. It's very similar to popular django-filter library and is designed to be used as a drop-in replacement (as much as it's possible) strictly tied to MongoEngine.

Full documentation on Read the docs.

PyPI Version

Supported Python versions

Build Status

Documentation Status

GPL-2.0-only OR LGPL-2.1-or-later

Coverage

Requirements

  • Python 3.7, 3.8, 3.9, 3.10 or 3.11.
  • MongoDB 3.x, 4.x, 5.x.
  • Django 2.2, 3.0, 3.1, 3.2, 4.0 or 4.1.

Installation

Install using pip:

pip install django-mongoengine-filter

Or latest development version:

pip install https://github.com/barseghyanartur/django-mongoengine-filter/archive/master.zip

Usage

Sample document

from mongoengine import fields, document
from .constants import PROFILE_TYPES, PROFILE_TYPE_FREE, GENDERS, GENDER_MALE

class Person(document.Document):

    name = fields.StringField(
        required=True,
        max_length=255,
        default="Robot",
        verbose_name="Name"
    )
    age = fields.IntField(required=True, verbose_name="Age")
    num_fingers = fields.IntField(
        required=False,
        verbose_name="Number of fingers"
    )
    profile_type = fields.StringField(
        required=False,
        blank=False,
        null=False,
        choices=PROFILE_TYPES,
        default=PROFILE_TYPE_FREE,
    )
    gender = fields.StringField(
        required=False,
        blank=False,
        null=False,
        choices=GENDERS,
        default=GENDER_MALE
    )

    def __str__(self):
        return self.name

Sample filter

import django_mongoengine_filter

class PersonFilter(django_mongoengine_filter.FilterSet):

    profile_type = django_mongoengine_filter.StringFilter()
    ten_fingers = django_mongoengine_filter.MethodFilter(
        action="ten_fingers_filter"
    )

    class Meta:
        model = Person
        fields = ["profile_type", "ten_fingers"]

    def ten_fingers_filter(self, queryset, name, value):
        if value == 'yes':
            return queryset.filter(num_fingers=10)
        return queryset

Sample view

With function-based views:

def person_list(request):
    filter = PersonFilter(request.GET, queryset=Person.objects)
    return render(request, "dfm_app/person_list.html", {"object_list": filter.qs})

Or class-based views:

from django_mongoengine_filter.views import FilterView

class PersonListView(FilterView):

    filterset_class = PersonFilter
    template_name = "dfm_app/person_list.html"

Sample template

<ul>
{% for obj in object_list %}
    <li>{{ obj.name }} - {{ obj.age }}</li>
{% endfor %}
</ul>

Sample requests

  • GET /persons/
  • GET /persons/?profile_type=free&gender=male
  • GET /persons/?profile_type=free&gender=female
  • GET /persons/?profile_type=member&gender=female
  • GET /persons/?ten_fingers=yes

Development

Testing

To run tests in your working environment type:

pytest -vrx

To test with all supported Python versions type:

tox

Running MongoDB

The easiest way is to run it via Docker:

docker pull mongo:latest
docker run -p 27017:27017 mongo:latest

Writing documentation

Keep the following hierarchy.

=====
title
=====

header
======

sub-header
----------

sub-sub-header
~~~~~~~~~~~~~~

sub-sub-sub-header
^^^^^^^^^^^^^^^^^^

sub-sub-sub-sub-header
++++++++++++++++++++++

sub-sub-sub-sub-sub-header
**************************

License

GPL-2.0-only OR LGPL-2.1-or-later

Support

For any security issues contact me at the e-mail given in the Author section.

For overall issues, go to GitHub.

Author

Artur Barseghyan <[email protected]>

django-mongoengine-filter's People

Contributors

barseghyanartur avatar lmoabreu avatar oussjarrousse avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

django-mongoengine-filter's Issues

Is it possible update this package to use Django 4.0?

ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation'
Import error 'force_text' from 'django.utils.encoding'

These problems occured by changing version of Django to 4.1.2, because these imports are differents.

bson.errors.InvalidDocument: cannot encode object: Decimal('3.5'), of type: <class 'decimal.Decimal'>

I have the follow document structure:

{
 ...
  "resultado": [
    {
      "badges": [
        {
          "codigo": "123",
          "url_imagem": "https://docs.mongoengine.org/apireference.html#mongoengine.fields.URLField",
          "valor": 3,
          "nome": "123",
          "descricao": "123",
          "master": false,
          
    }
   }
  ]
}

I declared the badge document as:

from mongoengine import (
    EmbeddedDocument, fields,
    DynamicDocument
)
class Badge(EmbeddedDocument):
    codigo = fields.StringField(required=False)
    url_imagem = fields.URLField(required=True)
    valor = fields.DecimalField(
        min_value=0,
        max_value=100,
        required=True
    )
    nome = fields.StringField(required=True)
    descricao = fields.StringField(required=True)
    master = fields.BooleanField(required=True)

I made a filter to filter the DecimalField on the EmbeddedDocument Badge:

import django_mongoengine_filter as mongofilter

class RelatorioFilterSet(mongofilter.FilterSet):
        badge_valor = mongofilter.NumberFilter(
        name='resultado__badges__valor'
    )

I'm trying to do the following request:

127.0.0.1:8000/relatorios/?badge_valor=3.5

But i always receive this error:

bson.errors.InvalidDocument: cannot encode object: Decimal('3.5'), of type: <class 'decimal.Decimal'>

I've already tried and observed that:

  • import Decimal128 from bson.decimal128 and save the decimalfield on the document with Decimal128('3.5') did not resolve the problem.
  • On the django shell Relatorio.objects.filter(resultado__badges__valor=3.5) works fine.
  • Somehow when i add some character to the filter param on the request it did not raise an error but return nothing (e.g: 127.0.0.1:8000/relatorios/?badge_valor=3.5g)

I don't know what i missing or if there's something wrong. Please, HELP!

AttributeError

when I use the django-mongoengine-filter just like I used in DRF,but there raise some errors:

class PersonSerializer(mongoserializers.DocumentSerializer):
    class Meta:
        model = Person
        fields = ["name"]

AttributeError: 'QuerySet' object has no attribute 'model'

Question: how to do `__in` queries?

For a document that contains a field with choices:

class UploadJob(Document):
    status = StringField(choices=(("queued", "Queued"), ("in_progress", "In Progress"), ("completed", "Completed"))) 

What is the preferred method of finding UploadJob.objects.filter(status__in=['queued', 'in_progress']) using this library?

Currently, if I submit a QueryDict with ?status='in_progress'&status='queued', it resolves to status[], which is not picked up by Django filter as an __in query.

Integrate with Django Rest Framework

There is a way to integrate it with the Django Rest classes ?

I've tried something like this but it just not working. The response always came empty and i can garatee that there's some documents to be returned.

class RelatorioViewSet(
    generics.ListCreateAPIView,
    FilterView
):
    filterset_class = RelatorioFilterSet
    serializer_class = RelatorioSerializer
    permission_classes = [AuthPermission]

    def get_queryset(self):
        return Relatorio.objects.all()

    def get(self, request, *args, **kwargs):
        filterset_class = self.get_filterset_class()
        self.filterset = self.get_filterset(filterset_class)
        page = self.paginate_queryset(self.filterset.qs)

        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(page, many=True)
        return Response(serializer.data)

django-filter: KeyError: 'required'

while using django_mongoengine_filter.FilterSet I got the following error:

  File "/Users/jesusch/git/jobq-api/venv/lib/python3.7/site-packages/django_filters/rest_framework/backends.py", line 139, in <listcomp>
    ) for field_name, field in filterset_class.base_filters.items()
KeyError: 'required'

problem:
django-filter Filtter object (meanwhile?) relies on having a self.extra['required'] property
see:
https://github.com/carltongibson/django-filter/blob/da4b64ea8dde19304b552592a32b343e9aefe9da/django_filters/filters.py#L79

while generating OpenAPI schemas this property is checked

django.forms.fields.Field() got multiple values for keyword argument 'help_text'

I need to add description of field filter in openapi format, but on pass help_text the following error is displayed in GET action of DRF (although works in openapi!)

from django_mongoengine_filter import FilterSet, MethodFilter

class UserFilter(FilterSet):
    gender = MethodFilter(action='get_gender', help_text='Gender of user (M = male, F = female)')

    class Meta:
        model = User
        fields = ['gender']

    def get_gender(self, queryset, name, value):
        return queryset.filter(gender=value)
TypeError at /api/v1/users/?gender=M
django.forms.fields.Field() got multiple values for keyword argument 'help_text'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.