1
Depends on your exact requirement and your version of Django, the answer may either setting the limit_choices_to
attribute of the foreign key, or customizing the ModelAdmin form:
Using limit_choices_to
Simply limit line choices to those matching linename == 'foo'
class Record(models.Model):
# ...
line = models.ForeignKey(LineType, limit_choices_to={'linename': 'foo'}))
Using a custom form
If an instance exists when instantiating the form, we can select it’s domain’s service’s lines as the queryset choices
class RecordAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(RecordAdminForm, self).__init__(*args, **kwargs)
# access object through self.instance...
if self.instance:
valid_lines = self.instance.domainname.service.line.objects.all()
self.fields['line'].queryset = valid_lines
class RecordAdmin(admin.ModelAdmin):
form = RecordAdminForm
# ...
Reference SO questions:
Source:stackexchange.com