filter by ForeignKey in django admin
I have the following situation. There is a model for project and one for project image.
class Project(models.Model): name = models.CharField(max_length=300) ... #some more fields class ProjectImage(models.Model): image = models.ImageField(upload_to = "uploads/") projekt = models.ForeignKey(Projekt)
Now, I'd like to be an admin panel user to filter out all projects in the admin area that don't have any image.
I already managed to have an icon in the overview that is green or red, wether it has an image attached or not. It works with a custom function on the model admin (This may not be the fastest solution but works ok).
class ProjectAdmin(admin.ModelAdmin): def image(self, obj): img = "no" images = ProjectImage.objects.only('id',).filter(project=obj) if images: img = "yes" return "<img src='"+ADMIN_MEDIA_PREFIX+"img/admin/icon-"+img+".gif' />" list_display = ('name', 'bild')
But AFAIK I can't use a similar method to just return a boolean and pass it as a custom filter.
I've also seen this: http://twigstechtips.blogspot.ch/2010/10/django-create-custom-admin-model-filter.html But it looks like a custom filter has to be attached to a model field and I don't have an image field in projects.
I there any other way to do this? thx
You should be able to do that with custom list filters, as of Django 1.4. You want something like this (untested):
from django.contrib.admin import SimpleListFilter class HasImageFiter(SimpleListFilter): title = 'has image' parameter_name = 'has_image' def lookups(self, request, model_admin): return ( ('Yes', 'Yes'), ('No', 'No'), ) def queryset(self, request, queryset): if self.value() == 'Yes': return queryset.filter(...) if self.value() == 'No': return queryset.filter(...) class ProjectAdmin(admin.ModelAdmin): list_filter = (HasImageFilter,)
I'll leave you to write your queryset filtering (comment if you get stuck and I'll fill it in).