carltongibson / django-filter

A generic system for filtering Django QuerySets based on user selections
https://django-filter.readthedocs.io/en/main/
Other
4.46k stars 769 forks source link

Fix fields #1442

Closed mayukorin closed 11 months ago

mayukorin commented 3 years ago

First, please see the Issue #1440 . This is about Issue #1440 "2. published_on" field is present in "Book model". I think it would be better to change it as following.

class Meta:
        model = Book
        # fields = ['published']
        fields = ['published_on']

Modified code was tested with following change on the test section of #1440.

# models.py
from django.db import models

...
class Book(models.Model):
    name = models.CharField(max_length=255)
    # published = models.DateTimeField(null=True)
    published_on = models.DateTimeField(null=True)
# views.py
from django_filters import BooleanFilter
...

class F(filters.FilterSet):

    published = BooleanFilter(field_name="published_on", method="filter_published")

    def filter_published(self, queryset, name, avlue):
        lookup = "__".join([name, "isnull"])
        print(lookup)
        return queryset.filter(**{lookup: False})

    class Meta:
        model = Book
        fields = ["published_on"]
        # fields = ["published"]
# tests.py
from rest_framework.test import APITestCase
from .models import Book
import datetime

class TestBookListAPIView(APITestCase):

    TARGET_URL = "/document/books/"

    def setUp(self):
        dt = datetime.datetime(
            2018, 2, 1, 12, 15, tzinfo=datetime.timezone(datetime.timedelta(hours=9))
        )
        self.book = Book.objects.create(name="django", published_on=dt)
        # self.book = Book.objects.create(name="django", published=dt)

    def test_list_success(self):
        params = {"published": "true"}
        response = self.client.get(self.TARGET_URL, params, format="json")

        expected_json = [
            {
                "id": self.book.id,
                "name": self.book.name,
                # "published": str(self.book.published).replace(" ", "T"),
               "published_on": str(self.book.published_on).replace(" ", "T"),
            }
        ]

        self.assertEqual(response.status_code, 200)
        self.assertJSONEqual(response.content, expected_json)

The result was successful.

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
published_on__isnull
.
----------------------------------------------------------------------
Ran 1 test in 0.469s

OK
Destroying test database for alias 'default'...