Note that there are some explanatory texts on larger screens.

plurals
  1. POLimit foreign key choices in select in an inline form in admin
    text
    copied!<p>The logic is of the model is: </p> <ul> <li>A <code>Building</code> has many <code>Rooms</code></li> <li>A <code>Room</code> may be inside another <code>Room</code> (a closet, for instance--ForeignKey on 'self') </li> <li>A <code>Room</code> can only be inside another <code>Room</code> in the same building (this is the tricky part) </li> </ul> <p>Here's the code I have: </p> <pre><code>#spaces/models.py from django.db import models class Building(models.Model): name=models.CharField(max_length=32) def __unicode__(self): return self.name class Room(models.Model): number=models.CharField(max_length=8) building=models.ForeignKey(Building) inside_room=models.ForeignKey('self',blank=True,null=True) def __unicode__(self): return self.number </code></pre> <p>and:</p> <pre><code>#spaces/admin.py from ex.spaces.models import Building, Room from django.contrib import admin class RoomAdmin(admin.ModelAdmin): pass class RoomInline(admin.TabularInline): model = Room extra = 2 class BuildingAdmin(admin.ModelAdmin): inlines=[RoomInline] admin.site.register(Building, BuildingAdmin) admin.site.register(Room) </code></pre> <p>The inline will display only rooms in the current building (which is what I want). The problem, though, is that for the <code>inside_room</code> drop down, it displays all of the rooms in the Rooms table (including those in other buildings).</p> <p>In the inline of <code>rooms</code>, I need to limit the <code>inside_room</code> choices to only <code>rooms</code> which are in the current <code>building</code> (the building record currently being altered by the main <code>BuildingAdmin</code> form). </p> <p>I can't figure out a way to do it with either a <code>limit_choices_to</code> in the model, nor can I figure out how exactly to override the admin's inline formset properly (I feel like I should be somehow create a custom inline form, pass the building_id of the main form to the custom inline, then limit the queryset for the field's choices based on that--but I just can't wrap my head around how to do it).</p> <p>Maybe this is too complex for the admin site, but it seems like something that would be generally useful... </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload