使用案例
建模:
class Company(models.Model):
company_name = models.CharField(max_length=50)
class UserProfile(models.Model):
user = models.OneToOneField(User)
company = models.ForeignKey(Company)
class Car(models.Model):
model_name = models.CharField(_(u"Model Name"))
car_type = models.CharField(_(u"Car Type"))
company = models.ForeignKey(Company)
class CarType(models.Model):
car_type = models.CharField(_(u"Car Type"))
company = models.ForeignKey(Company)
查看:
def main_page_view(request):
profile = request.user.get_profile()
AllCarsCreatedByTheCompany = profile.company.car_set.all()
这种方法已经完美,但问题是CarType。
问题:
- 每家公司生产不同类型的汽车。感谢公司foreignkey,它已经与另一家公司分开了。
我做了什么:
def new_car_view(request):
profile = request.user.get_profile()
if request.method == 'POST':
form = CarForm(request.POST)
if form.is_valid():
car = Car.objects.create(
model_name=form.cleaned_data['model_name'],
company=profile.company
)
car.save()
return HttpResponseRedirect('/')
else:
form = CarForm()
variables = RequestContext(request, {'form':form})
return render_to_response('car_add.html', variables)
形式:
class CarForm(ModelForm):
class Meta:
model = Car
exclude = ('company')
然而,表格显示下拉列表中的所有车型,而不是公司外键过滤的车型。我错过了什么?
答案 0 :(得分:1)
您可以在init中修改选择。这是一个例子:
class CarForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CarForm, self).__init__(*args, **kwargs)
# limit selection list to just items for this account
self.fields['cartypes'].queryset = CarType(company=company)
此外,将公司作为隐藏字段包含在内,以便您可以引用它而不是将其排除。