24

I have two models implemented like

class A(models.Model):
    a_name = models.CharField(max_length=50)

class B(models.Model):
    a = models.ForeignKey(A)
    b_tag = models.CharField(max_length=50)
    user=models.ForeignKey(User)             # stores username

Now I define an A admin and register it with B as a subclass to TabularInline. I wonder if it is possible somehow to filter the list of B objects before the inline formset is rendered, so not all B objects related to A get into the formset, only ones whose user parameter matches the currently logged in user shows up!

djvg
  • 11,722
  • 5
  • 72
  • 103
krishnan
  • 263
  • 1
  • 2
  • 7

1 Answers1

47

Use the get_queryset method: https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset

Should look like:

class BAdmin(admin.TabularInline):
    ...

    def get_queryset(self, request):
        qs = super(BAdmin, self).get_queryset(request)
        return qs.filter(user=request.user)
djvg
  • 11,722
  • 5
  • 72
  • 103
noamk
  • 1,179
  • 13
  • 15
  • thanks a bunch .It worked like a charm! . If i could trouble you for one more thing , Why does our overridden function call its superclass TabularInline. – krishnan Jun 03 '15 at 10:21
  • The superclass call gets the initial queryset that filters on the A model. – noamk Jun 03 '15 at 16:45
  • In general, this is a great method overall for filtering TabularInline and StackedInline. – user3507825 Mar 18 '21 at 21:46