D
D
Denis Pupchenko2017-06-19 09:21:07
Django
Denis Pupchenko, 2017-06-19 09:21:07

How to set up a filter in the admin panel?

I use the django MPTT module, when specifying a filter, it displays records only of the current tree level, if the current tree node has child nodes that have records, then it does not display them.

class Section(MPTTModel):
    section_text = models.CharField(verbose_name='Название раздела', max_length=100)
    parent = TreeForeignKey(verbose_name='Родительский Раздел', to='self', null=True, blank=True, related_name='children')

class Question(models.Model):
    section = models.ForeignKey(Section,verbose_name='Родительский раздел')
    question_text = HTMLField(verbose_name='Описание вопроса')

admin.py
class QuestionAdmin(admin.ModelAdmin):
    list_filter =(
        ('section', TreeRelatedFieldListFilter),
    )

For example, there is such a tree
7bf669b941c2406db40a056092cb14f8.png
. Records from Question are attached to the node of level 3, if you select nodes of level 1 or 2, then the records of node 3 are not displayed, if you select level 3, then the records are displayed, i.e. records of only the current node are displayed, if the current node has child nodes of a lower level, then the records belonging to them are not displayed.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
un1t, 2017-06-26
@un1t

You need to write your custom filter. Here is the documentation on how to create your own filter.
https://docs.djangoproject.com/en/1.11/ref/contrib...
You need to write your own queryset (sql query) in the filter.
To understand what query to write you need to read about nested sets .
Selecting offspring:
You can also look at the source code for the get_descendants method from mptt
https://github.com/django-mptt/django-mptt/blob/ma...
It should look something like this:

section = get_objects_or_404(Section, id= request.GET.get ...

Section.objects.filter(
    tree_id=section.tree_id
    left__gte=section.left,
    left__lte=section.right
).order_by('left')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question