在 Django ModelForm 中过滤外键选择
假设您定义了以下模型:
class Company(models.Model): name = ... class Rate(models.Model): company = models.ForeignKey(Company) name = ... class Client(models.Model): name = ... company = models.ForeignKey(Company) base_rate = models.ForeignKey(Rate)
目标是为了确保在创建客户端时,可用的费率选择仅限于父级内的费率选择
在Django 1.0 forms.py文件中:
from models import * from django.forms import ModelForm class ClientForm(ModelForm): class Meta: model = Client def __init__(self, company_id, *args, **kwargs): '''Filter the rate choices to only include those for the specified company''' super(ClientForm, self).__init__(*args, **kwargs) self.fields['base_rate'].queryset = Rate.objects.filter(company_id=company_id)
在views.py中:
from django.shortcuts import render_to_response, get_object_or_404 from models import * from forms import * def addclient(request, company_id): the_company = get_object_or_404(Company,>
通过过滤分配给'rate的QuerySet ' 字段,'base_rate' 外键的可用选择仅限于指定公司内的适当费率。
以上是如何根据母公司过滤 Django ModelForm 中的外键选择?的详细内容。更多信息请关注PHP中文网其他相关文章!