Search code examples
djangodjango-modelsdjango-admindjango-manage.py

overriding def queryset doesn't work when pulling foreignkey items?


I've got a modeladmin like this

class StudentAdmin(admin.ModelAdmin):
    date_hierarchy = 'dob'

    def queryset(self, request):
        queryset = Student.objects.filter(created_by=request.user)
        return queryset

class ClassroomAdmin(admin.ModelAdmin):
    list_display = ('name',)
    ordering = ('name',)

    def queryset(self, request):
        queryset = Classroom.objects.filter(created_by=request.user)
        return queryset

As you can see I only want students and classrooms which have been created by the logged in user to appear. On the change list page this query seems to work fine. If I have not created the classrooms then I can't see them.

no classrooms

But when I go to the 'Add new' form (for a student object for example) then you see all the classrooms being listed on the form even if the logged in user hasn't created them( this list should be empty for this user as class1 was created by someone else)(Classroom is a FK to Student) .

classrooms

What am I missing?


Solution

  • for limiting the queryset for foreign keys, have a look at formfield_for_foreignkey