如何在django admin中限制内联模型的查询集

时间:2022-09-12 09:09:58

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 a 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 do A gets into the formset only ones whose user parameter matches the currently logged in user shows up!

现在我定义一个A管理员并将其注册为B作为TabularInline的子类。我想知道是否有可能以某种方式在呈现内联formset之前过滤B对象列表,因此并非所有B对象都相关做A进入formset只显示其用户参数与当前登录用户匹配的用户!

1 个解决方案

#1


15  

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

使用get_queryset方法: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)

#1


15  

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

使用get_queryset方法: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)