Django CreateView 过滤外键
我需要一些帮助。我正在用 Django 1.6 和 Python 3.4 写一个应用。
我的模型:
class Account(models.Model):
number = models.IntegerField()
name = models.CharField(max_length = 100)
level = models.IntegerField()
parent_account = models.ForeignKey(Account, null=True, blank=True)
我的视图:
class InvoiceCreateView(CreateView):
model = Account
template_name = 'account/templates/create.html'
success_url = reverse_lazy('account_list')
当我创建一个新账户时,会出现一个下拉列表,让我选择父账户,一切都很好,但我想让这个下拉列表只显示等级为 2 的账户(比如说),而不是所有账户。
类似这样的:
account.object.all().filter(level=2)
提前谢谢你们!
2 个回答
0
2
你可以创建一个自定义的表单,并在你的视图中设置一个叫做 form_class 的变量,像这样:
class InvoiceCreateView(CreateView):
model = Account
form_class = AccountForm
template_name = 'account/templates/create.html'
success_url = reverse_lazy('account_list')
在你的表单中(我把它命名为 AccountForm),你可以根据需要定义父字段:
class AccountForm(forms.ModelForm):
class Meta(object):
model = Account
parent = forms.ModelChoiceField(queryset=Account.objects.filter(level=2))