Reputation: 3230
I got two models which are related via ForeignKey in Django. (I am using Django 1.3)
Class Person(models.Model):
# some fields here like name, gender, etc...
Class Course(models.Model):
# some fields here
contact = models.ForeignKey(Person, blank=True, null=True)
In the admin changelist view for the Courses I want to be able to filter the Courses by the ForeignKey contact. In the admin.py i got:
class CourseAdmin(admin.ModelAdmin):
list_filter = ('contact',)
This work very well. I can filter the Courses by all available Contacts. Now I would like to display only those contacts that actually have a Course attached to them. I read here on SO to implement CustomFilters by creating a custom FilterSpec. I dont know wheter this is the right direction, because I only need to further filter the queryset that is used to display the choices for the contacts.
In the shell I get the desired queryset by this:
contacts=Person.objects.filter(course__in=Course.objects.all()).distinct()
I already read that you can easily achieve this in 1.4, but I am still bound to 1.3 Can someone please point me into the right direction? Thank you!
Upvotes: 0
Views: 424
Reputation: 8482
Django 1.3 also supports Filters, but the filter classes were moved/renamed in 1.4. And using a FilterSpec is the way to achieve your goal. You not only need to filter the queryset, but to handle properly the applied filter from QueryString. So go ahead with filters. Here is a very good snippet, that handles the FK filtering, and has decent options: http://djangosnippets.org/snippets/2260/
Upvotes: 1