1

I have the following Models:

class Organizations(models.Model):
    name = models.CharField(max_length=30,unique=True)

class Postcodes(models.Model):
    organization = models.ForeignKey(Organizations,on_delete=models.PROTECT)
    postcode = models.PositiveBigIntegerField()

class Agent(models.Model):
    organization = models.ForeignKey(Organizations,on_delete=models.PROTECT)
    name = models.CharField(max_length=50)

class AgentPostcodes(models.Model):
    agent= models.ForeignKey(Agent,on_delete=models.PROTECT)
    postcode = models.ForeignKey(Postcodes,on_delete=models.PROTECT)

and admin.py is

class AgentPostcodesInline(admin.TabularInline):
    model = AgentPostcodes

class AgentAdmin(admin.ModelAdmin):
    list_display = ['organization','name']
    inlines = [AgentPostcodesInline]    

How can I have the inline form fields filtered based on organization for postcodes related to that organization only. Currently it shows postcodes for all organizations even not related to the agent.

1 Answers1

0

Override TabularInline(InlineModelAdmin) get_queryset method similar to what is described in documentation:

ModelAdmin.get_queryset(request)

The get_queryset method on a ModelAdmin returns a QuerySet of all model instances that can be edited by the admin site. One use case for overriding this method is to show objects owned by the logged-in user:

class MyModelAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(author=request.user)
iklinac
  • 14,944
  • 4
  • 28
  • 30
  • Additionally this might help you further https://stackoverflow.com/questions/32150088/django-access-the-parent-instance-from-the-inline-model-admin – iklinac Sep 21 '20 at 15:25
  • Inline how to get the organization from main form? that is the question in short. get_form and form.base_field["organization"], selected value I can not get and using formfield_for_foreignkey() can have again queryset for the field not the single value. :( – Azhar Jadoon Sep 22 '20 at 14:22