0

I'm trying to limit the items available to choose from a dropdown list in the admin panel for a given model.

At the moment, I overrode the save method to throw a valueerror if conditions are not met, but this is an ugly solution IMO. At the time I wrote that, I was not aware of proxy models, which seem like the solution, at least according to this answer.

I have a model Entry, so I created a proxy model like so:

class ApprovedEntries(Case):
    class Meta:
        proxy = True
        verbose_name = 'Entry'
        verbose_name_plural = 'Entries'

    def get_queryset(self, request):
        qs = Entry.objects.filter(assigned_contestant__approved='True', assigned_contestant__active='True')
        return qs

Then in my admin.py I replaced the existing entry to register the Entry model with:

admin.site.register(ApprovedEntries)

However, this seems to have no effect. Only the unfiltered list of Entry objects is returned. Is something additional needed to 'activate' a proxy model? Is there a better solution to my problem?

Jake Rankin
  • 714
  • 6
  • 22

1 Answers1

0

You can override the get_queryset on the admin class. I do this for a few reasons, mainly for efficiency in getting related data.

class CharityAdmin(admin.ModelAdmin):
    """ Charity model admin """
    list_display = (
        'id',
        'enabled',
    )
    list_filter = (
        'enabled',
    )
    readonly_fields = (
        'created',
        'modified',
    )
    ordering = (
        'name',
        '-id',
    )

    def get_queryset(self, request):
        """
        Custom queryset to efficiently pull in the data
        """
        qs = super().get_queryset(request)
        setattr(qs, '__class__', CharityAdminQuerySet)
        return getattr(qs, '_clone')()
markwalker_
  • 12,078
  • 7
  • 62
  • 99