Wednesday, October 24, 2012

Django admin select field limit, based on another ForeignKey fields

Let say you have models:

class CompanyInfo(models.Model):
    name = models.CharField('Company name',max_length=250)

class Staff(models.Model):
    company_name = models.ForeignKey(CompanyInfo)
    date = models.DateField()
    name = models.CharField('Name', max_length=30, )

class Relation(models.Model):
    company_name = models.ForeignKey(CompanyInfo)
    who = models.ForeignKey(Staff, related_name="who", blank=True)
    with_whom = models.ForeignKey(Staff, related_name="with_whom", blank=True)

And you want limit staff list in Relation form for only staff, who related for that company by field company_name.
This admin.py helps you solve that problem:

# -*- coding:utf-8 -*-
from models import Staff, Relation
from django.contrib import admin
from django import forms

class RelationForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(RelationForm, self).__init__(*args, **kwargs)
        qs = Staff.objects.filter(company_name = self.instance.company_name)
        self.fields['who'].queryset = qs
        self.fields['with_whom '].queryset = qs

class RelationAdmin(admin.ModelAdmin):
    form = RelationForm

admin.site.register(Relation, RelationAdmin)

Do you know, how do it for new entry? :)

No comments:

Post a Comment