djangodjango-modelsdjango-admin

Show a subset of my models data in Django Admin


my database model is like

class Restaurant(models.Model):
    email_sent = models.BooleanField(null=True, default=False)
    rest_owner = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='rest_owner')
    is_approved = models.BooleanField(null=False, default=False)

I want to create a separate table where I can show data of just fields where is_approved=0 . its simple in django Site. But I am unable to find a way to do this in djangoAdmin side. Or I have to make a custom admin for this ?


Solution

  • Add this to your admin.py:

    from django.contrib import admin
    from .models import Restaurant
    
    def mark_approved(modeladmin, request, queryset):
        queryset.update(is_approved=True)
    mark_approved.short_description = "Mark selected restaurants as approved."
    
    class RestaurantAdmin(admin.ModelAdmin):
        list_filter = ('is_approved',)
        actions = ('mark_approved',)
    
    admin.site.register(Restaurant, RestaurantAdmin)
    

    You should then be able to go to your Django admin, and see a restaurant link there. From there you can filter your list on wether is_approved is True or not.

    To mark restaurants as approved, select them in the list, and click on the action dropdown, as shown in the screenshot in the Django docs