Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Add geometry filters #710

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

shmoon-kr
Copy link
Contributor

@shmoon-kr shmoon-kr commented Feb 18, 2025

Description

Added GeometryLookupFilter type so that spatial filters available in GeoDjango can be used in strawberry_django.

Types of Changes

  • [O] New feature

Issues Fixed or Closed by This PR

Checklist

  • [V] My code follows the code style of this project.
  • [V] My change requires a change to the documentation.
  • [V] I have updated the documentation accordingly.
  • [V] I have read the CONTRIBUTING document.
  • I have added tests to cover my changes.
  • [V] I have tested the changes and verified that they work and don't break anything (as well as I can manage).

Summary by Sourcery

Adds support for spatial filters from GeoDjango within strawberry-django. It introduces a new GeometryFilterLookup type and integrates it into the existing filter system, allowing users to filter data based on geographical relationships.

New Features:

  • Adds GeometryLookupFilter type to enable the use of spatial filters from GeoDjango within strawberry-django, allowing filtering based on geographical relationships.

Enhancements:

  • Adds support for Geometry types to the filter lookup, allowing filtering of fields based on their spatial properties.

Copy link
Contributor

sourcery-ai bot commented Feb 18, 2025

Reviewer's Guide by Sourcery

This pull request introduces the GeometryFilterLookup input type, enabling spatial filtering capabilities in strawberry-django by leveraging GeoDjango's spatial lookups. The implementation conditionally includes this functionality only when GeoDjango is available, ensuring compatibility for users without GDAL installed.

Class diagram for GeometryFilterLookup

classDiagram
    class GeometryFilterLookup {
        bbcontains: Geometry
        bboverlaps: Geometry
        contained: Geometry
        contains: Geometry
        contains_properly: Geometry
        coveredby: Geometry
        covers: Geometry
        crosses: Geometry
        disjoint: Geometry
        equals: Geometry
        exacts: Geometry
        intersects: Geometry
        isempty: bool
        isvalid: bool
        overlaps: Geometry
        touches: Geometry
        within: Geometry
        left: Geometry
        right: Geometry
        overlaps_left: Geometry
        overlaps_right: Geometry
        overlaps_above: Geometry
        overlaps_below: Geometry
        strictly_above: Geometry
        strictly_below: Geometry
    }
    note for GeometryFilterLookup "This class is only available when GeoDjango is installed"
Loading

File-Level Changes

Change Details Files
Adds a GeometryFilterLookup input type for filtering based on GeoDjango's spatial lookups.
  • Introduces GeometryFilterLookup with spatial lookup fields like contains, intersects, within, etc.
  • Conditionally defines GeometryFilterLookup and exports it in __init__.py only when GeoDjango is available to prevent errors when GDAL is not installed.
  • Adds a conditional check for Geometry scalar type to use GeometryFilterLookup when using new filters.
  • Adds Geometry scalar type to be used with spatial lookups.
strawberry_django/fields/filter_types.py
strawberry_django/__init__.py
strawberry_django/fields/types.py

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @shmoon-kr - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding a test case to ensure that the GeometryFilterLookup works as expected.
  • It might be worth extracting the GeometryFilterLookup try/except block into a separate function or module to improve readability.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@@ -557,9 +558,11 @@
):
if using_old_filters:
field_type = filters.FilterLookup[field_type]
elif type(field_type) is ScalarWrapper and field_type._scalar_definition.name in ("Point", "LineString", "LinearRing", "Polygon", "MultiPoint", "MultilineString", "MultiPolygon", "Geometry"):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Consider using isinstance for type checking of ScalarWrapper.

Using 'type(field_type) is ScalarWrapper' might be too strict if subclasses of ScalarWrapper should also match. Switching to isinstance(field_type, ScalarWrapper) could provide a more flexible and robust check.

Suggested change
elif type(field_type) is ScalarWrapper and field_type._scalar_definition.name in ("Point", "LineString", "LinearRing", "Polygon", "MultiPoint", "MultilineString", "MultiPolygon", "Geometry"):
elif isinstance(field_type, ScalarWrapper) and field_type._scalar_definition.name in ("Point", "LineString", "LinearRing", "Polygon", "MultiPoint", "MultilineString", "MultiPolygon", "Geometry"):

pass
else:
@strawberry.input
class GeometryFilterLookup(Generic[T]):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider dynamically generating the geometry fields to reduce code duplication.

Consider reducing the repetitive field definitions by generating the geometry fields dynamically. For example, you can define a list of method names and then use a helper to build your fields. This will reduce the nesting and repetitive code without changing functionality. For instance:

try:
    from django.contrib.gis.geos import GEOSGeometry
except ImproperlyConfigured:
    # If gdal is not available, skip.
    pass
else:
    GEO_FIELD_TYPE = Optional[Annotated["Geometry", strawberry.lazy(".types")]]
    geometry_methods = [
        "bbcontains", "bboverlaps", "contained", "contains", "contains_properly",
        "coveredby", "covers", "crosses", "disjoint", "equals", "exacts",
        "intersects", "overlaps", "touches", "within", "left", "right",
        "overlaps_left", "overlaps_right", "overlaps_above", "overlaps_below",
        "strictly_above", "strictly_below",
    ]

    def _build_geometry_fields():
        fields = {name: UNSET for name in geometry_methods}
        fields.update({
            "isempty": filter_field(description=f"Test whether it's empty. {_SKIP_MSG}"),
            "isvalid": filter_field(description=f"Test whether it's valid. {_SKIP_MSG}"),
        })
        return fields

    GeometryFields = _build_geometry_fields()
    GeometryFilterLookup = strawberry.input(
        type("GeometryFilterLookup", (Generic[T],), GeometryFields)
    )

This refactoring maintains all functionality while reducing the duplication and nesting in your class definition.

@codecov-commenter
Copy link

Codecov Report

Attention: Patch coverage is 87.80488% with 5 lines in your changes missing coverage. Please review.

Project coverage is 88.10%. Comparing base (dad9316) to head (17ce3f8).

Files with missing lines Patch % Lines
strawberry_django/__init__.py 66.66% 2 Missing ⚠️
strawberry_django/fields/filter_types.py 93.75% 2 Missing ⚠️
strawberry_django/fields/types.py 66.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #710      +/-   ##
==========================================
- Coverage   88.11%   88.10%   -0.01%     
==========================================
  Files          42       42              
  Lines        3853     3894      +41     
==========================================
+ Hits         3395     3431      +36     
- Misses        458      463       +5     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants