0

Good evening,

I created a new database table in models.py (persons):

class persons(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
active = models.IntegerField()

Now I added this code in the admin.py:

class personsAdmin(admin.ModelAdmin):
 list_display = ('name','age')

admin.site.register(persons, personsAdmin)

In the admin area it shows me every person I added to the database. So far so good, but now I want to see only the person where active > 0. Can I do this in Django admin.py?

James
  • 1
  • 2

2 Answers2

0

Make the following update:

class personsAdmin(admin.ModelAdmin):
 list_display = ('name','age', 'active')
 list_filter = ('active',) # Not, the trailing comma is intentional, it is so it becomes a tuple.
admin.site.register(persons, personsAdmin)

This will allow you to filter by the active field in the view.

Salaah Amin
  • 382
  • 3
  • 14
  • Is there an option aswell only to display the active (active==1) ones ? And don`t show the inactive ones (active!=1) at all ? With the filter I am still able to see the inactive ones, since I can filter them :( – James Jul 27 '21 at 00:42
0

Thanks to bdbd I could reuse some of the code to get my answer:

class customerAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super(personsAdmin, self).get_queryset(request)
        return qs.filter(active=1)
    list_display = ('name','age',)
James
  • 1
  • 2