Django - 在Admin过滤器中使用模型管理器方法

时间:2018-05-04 03:06:37

标签: django django-admin

我正在使用Django 2.0

我在 models.py

中有一个带自定义管理器的模型类
class MockTestQuerySet(models.query.QuerySet):
    def upcoming(self):
        return self.filter(start_date__gte=datetime.now())

    def past(self):
        return self.filter(end_date__lte=datetime.now())


class MockTestManager(models.Manager):
    def get_queryset(self):
        return MockTestQuerySet(self.model, self._db)

    def upcoming_tests(self):
        return self.get_queryset().upcoming()

    def past_tests(self):
        return self.get_queryset().past()

    def is_past(self, mock_pk):
        mock_test = self.get_queryset().past().filter(pk=mock_pk).first()
        if mock_test is not None:
            return True

        return False

    def is_future(self, mock_pk):
        mock_test = self.get_queryset().upcoming().filter(pk=mock_pk).first()
        if mock_test is not None:
            return True

        return False


class MockTest(models.Model):
    title = models.CharField(max_length=250, null=False, blank=False)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()
    modified = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    objects = MockTestManager()

    class Meta:
        db_table = 'mock_tests'
        ordering = ['start_date']

现在,我正在使用管理模块,并希望创建过滤器,通过调用past_tests()upcoming_tests()

来过滤即将或过去的测试

直到现在,我已经在 admin.py

中尝试了这一点
class InPast(admin.SimpleListFilter):
    def lookups(self, request, model_admin):
        pass

    title = _('Past Mock Tests')
    parameter_name = 'past'

    def queryset(self, request, queryset):
        return queryset.past_tests()


@admin.register(MockTest)
class MockTestAdmin(admin.ModelAdmin):
    list_display = ['title', 'start_date', 'end_date', 'duration']

    list_filter = [
        InPast
    ]

我知道,我做错了但无法弄明白该怎么做。

0 个答案:

没有答案