DJANGO, пользовательский LIST_FILTER - PullRequest
0 голосов
/ 19 февраля 2019

Я использую только администратора django и пытаюсь создать собственный фильтр, в котором необходимо отфильтровать дату другой модели.

Мои модели

class Avaria(models.Model):
 .....
class Pavimentacao(models.Model):

    avaria = models.ForeignKey(Avaria, related_name='AvariaObjects',on_delete=models.CASCADE)
    date= models.DateField(blank=True,null=True)

AvariaAdmin

class AvariaAdmin(admin.ModelAdmin):
    list_filter = ('')

Ответы [ 2 ]

0 голосов
/ 19 февраля 2019

Например, допустим, у вас есть модель, и вам нужно добавить пользовательский ContentTypeFilter к администратору модели.Вы можете определить класс, который наследует SimpleListFilter и определить lookups и queryset на основе ваших требований и добавить этот класс к list_filter, например

list_filter = [ContentTypeFilter]

См. документы

Пример определения класса приведен ниже:

class ContentTypeFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('content type')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'type'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        models_meta = [
            (app.model._meta, app.model.__name__) for app in get_config()
        ]
        return (item for item in models_meta)

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """

        if not self.value():
            return

        model = apps.get_model(self.value())
        if model:
            return queryset.models(model)
0 голосов
/ 19 февраля 2019

Вы должны добавить поле, которое хотите отфильтровать.В вашем примере, если вы хотите фильтровать по дате, вы помещаете list_filter ('date').Не забудьте зарегистрировать администратора модели как показано здесь

...