在 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中文網其他相關文章!