In my Django application I have Guest user accounts that are created for all unregistered users (they all have email=’guest@mysite.com’). At the same time I create some demo objects related to the Guest account.
These objects live in the same table (have the same model) as objects for registered users. And I have more that one type (model) of these objects like:
class Object1(models.Model):
user = ForeignKey(...)
...
class Object2(models.Model):
user = ForeignKey(...)
...
And what I would like to achieve is to filter out all objects related to guest accounts when I view them in django admin.
Right now I subclass django.contrib.admin.views.main.ChangeList and override get_query_set method to do the required exclude, and I redefine get_changelist method of django’s ModelAdmin class at runtime:
class FilteredChangeList(ChangeList):
def get_query_set(self):
qs = super(FilteredChangeList, self).get_query_set()
if is_related_to(self.model, Profile):
qs = qs.exclude(user__email='guest@mysite.com')
return qs
def my_getchangelist(self, request, **kwargs):
return FilteredChangeList
ModelAdmin.get_changelist = my_getchangelist
I suppose redefining django’s methods at runtime is a bad practice, so is there any correct solution for the problem?
Guess you are doing a lot more work than necessary. You could also create your own
ModelAdminclass and overwrite itsquerysetmethod, no need to construct your ownChangeListclass:You could then either register your models directly with this new admin class –
admin.site.register(Model, MyFilteredAdmin)– or create subclasses that inherit fromMyFilteredAdmininstead from django’sModelAdmin.