Home > Software design >  Filter by a virtual name in the admin site
Filter by a virtual name in the admin site

Time:09-07

Django4.1

class Exercise(NameMixin,
               UrlMixin,
               PriorityMixin,
               CommentMixin):
    unit = models.ForeignKey('vocabulary_units.Unit',
                             on_delete=models.CASCADE,
                             null=True, )



class Phrase(models.Model):

    exercise = models.ForeignKey('vocabulary_exercises.Exercise',
                                 on_delete=models.CASCADE,
                                 null=True,
                                 blank=False)

    @property
    def unit(self):
        result = self.exercise.unit
        return result

A phase belongs to an exercise, excercise belongs to a unit.

The problem is that in the admin site I'd like to organise for phrases a filter by unit.

Is it possible?

CodePudding user response:

You can use '__' lookup method in the list_filter fields. Also you didn't post how the Unit model looks, this code will filter in IDs basically, you probably will want to use exercise__unit__name or similar:

from django.contrib import admin


class PhraseAdmin(admin.ModelAdmin):
    list_filter = ['exercise__unit']

Check also this answer

  • Related