Is this correct?
它是否正确?
class Customer(models.Model):
account = models.ForeignKey(Account)
class Order(models.Model):
account = models.ForeignKey(Account)
customer = models.ForeignKey(Customer, limit_choices_to={'account': 'self.account'})
I'm trying to make sure that an Order form will only display customer choices that belong to the same account as the Order.
我正在尝试确保订单表单只显示与订单属于同一帐户的客户选择。
If I'm overlooking some glaring bad-design fallacy, let me know.
如果我忽略了一些明显糟糕的设计谬误,请告诉我。
The main thing I'm concerned with is:
我关心的主要是:
limit_choices_to={'account': 'self.account'}
3 个解决方案
#1
18
The only answer to 'is it correct' is 'does it work when you run it?' The answer to that of course is no, so I don't know why you're asking here.
“它是否正确”的唯一答案是“运行时它是否有效?”答案当然是否定的,所以我不知道你为什么在这里问。
There's no way to use limit_choices_to dynamically to limit based on the value of another field in the current model. The best way to do this is by customising the form. Define a ModelForm subclass, and override the __init__
method:
根据当前模型中另一个字段的值,无法动态使用limit_choices_to来限制。最好的方法是自定义表单。定义ModelForm子类,并覆盖__init__方法:
class MyOrderForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyOrderForm, self).__init__(*args, **kwargs)
if 'initial' in kwargs:
self.fields['customer'].queryset = Customer.objects.filter(account=initial.account)
#2
0
You should set choices
field of your order form (inherited from ModelForm
) in the constructor.
您应该在构造函数中设置订单表单的选择字段(继承自ModelForm)。
#3
-1
limit_choices_to={'account': 'self.account'}
is wrong, since foreign key to customer cannot point to Account
.
limit_choices_to = {'account':'self.account'}是错误的,因为客户的外键不能指向Account。
#1
18
The only answer to 'is it correct' is 'does it work when you run it?' The answer to that of course is no, so I don't know why you're asking here.
“它是否正确”的唯一答案是“运行时它是否有效?”答案当然是否定的,所以我不知道你为什么在这里问。
There's no way to use limit_choices_to dynamically to limit based on the value of another field in the current model. The best way to do this is by customising the form. Define a ModelForm subclass, and override the __init__
method:
根据当前模型中另一个字段的值,无法动态使用limit_choices_to来限制。最好的方法是自定义表单。定义ModelForm子类,并覆盖__init__方法:
class MyOrderForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyOrderForm, self).__init__(*args, **kwargs)
if 'initial' in kwargs:
self.fields['customer'].queryset = Customer.objects.filter(account=initial.account)
#2
0
You should set choices
field of your order form (inherited from ModelForm
) in the constructor.
您应该在构造函数中设置订单表单的选择字段(继承自ModelForm)。
#3
-1
limit_choices_to={'account': 'self.account'}
is wrong, since foreign key to customer cannot point to Account
.
limit_choices_to = {'account':'self.account'}是错误的,因为客户的外键不能指向Account。