How to limit the set of queries of the embedded model in django admin

I have two models implemented as

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 the administrator A and register it with B as a subclass for TabularInline. I wonder if it is possible to somehow filter the list of objects B before displaying the built-in set of forms, therefore, not all objects associated with B get into the set of forms, only those whose user parameter matches the current registered user will be displayed!

+6
source share
1 answer

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

It 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) 
+15
source

Source: https://habr.com/ru/post/988438/


All Articles