1

The below is my model,

class Employee(models.Model):
    name = models.CharField(max_length=100)
    sex = models.PositiveIntegerField(choices=choices(Type))

Enum class is

class Type(Enum):
    Male = 0
    Female = 1

Now coming to our main model

class Tournament(models.Model):
    player_name = models.ForeignKey(Employee)

My admin is

@admin.register(Tournament, site=admin.site)
class TournamentAdmin(admin.ModelAdmin):
    list_display = ('player_name')

The requirement is I only want to get Male players in My admin page in the field player_name.

How to filter from ENUM class to get only male players name in Django admin field. Please help me. Thank you!

Learner
  • 319
  • 2
  • 4
  • 9
  • From where the **`choices()`** is importing? – JPG Feb 13 '20 at 06:36
  • Hey Arakkal, Choices is coming from ENUM class. I've imported and everything is fine. Just need to filter only one value or hard code it to get only men. – Learner Feb 13 '20 at 06:40
  • you need to create a custom filter for your use case. please refer : https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter – N.Moudgil Feb 13 '20 at 06:48
  • @Learner I asked because of curiosity. Can you add the reference of `choice()` function? – JPG Feb 13 '20 at 06:55

2 Answers2

1

I have done it by overriding formfield_for_foreignkey method in admin. And if you have more fields where the filter needs to be applied, just add more if blocks and filter from related models(by importing the models).

And if there is a ForeignKey relationship, you need to go from child to parent class using __ between the fields of child to parent

@admin.register(Tournament, site=admin.site)
class TournamentAdmin(admin.ModelAdmin):
    list_display = ('player_name')

    def formfield_for_foreignkey(self,db_field,request,**kwargs):
        if db_field.name == 'player_name':
            kwargs['queryset'] = Employee.objects.filter(type=Type.Male.value)
        return super().formfield_for_foreignkey(db_field,request,**kwargs)
Learner
  • 319
  • 2
  • 4
  • 9
0

Using the reference Django admin.SimpleListFilter . you can try this:

from django.contrib import admin

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

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

    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.
        """
       return (
        (0, _('Male')),
        (1, _('Female')),
        )

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

class TournamentAdmin(admin.ModelAdmin):
    list_filter = (GenderListFilter,)

Hope it helps.

N.Moudgil
  • 709
  • 5
  • 11
  • Hey in the method lookups we need to return only (0, _('Male')) right. And what are the title and parameter_name which is gender here? Just wondering how they will be shown – Learner Feb 13 '20 at 07:08
  • @Learner title will be shown on the right side of the admin page. you can refer to the link provided for details. – N.Moudgil Feb 13 '20 at 07:11
  • Yea I saw that. But my requirement is once I click on TournamentAdmin. player_name column will show. Now in my case it is showing all the men and women once we click on the column. I only need to show men there in the column. Will this list_display will work there? – Learner Feb 13 '20 at 07:13
  • We need not to show anything on the sidebar or whatsoever. We need to get only values related to men in the column, player_name in admin. So it has nothing to do with the admin page itself. It has to do with the column values only – Learner Feb 13 '20 at 07:17
  • for that, You can override `get_queryset` method in your model admin class. – N.Moudgil Feb 13 '20 at 08:46
  • @Learner check this: https://stackoverflow.com/questions/12354099/override-default-queryset-in-django-admin – N.Moudgil Feb 13 '20 at 08:57