Django:limit_choices_to(这是正确的) [英] Django: limit_choices_to (Is this correct)
问题描述
类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'})
我试图确定订单表单只显示与订单属于同一帐户的客户选择。
如果我忽略了一些显而易见的糟糕设计谬误,请告诉我。 b
$ b
我主要关心的是:
$ p $ limit_choices_to = {'account' :'self.account'}
这是正确的是它运作时,它运行吗?答案当然是不,所以我不知道你为什么问这里。
__ 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)
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'}
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:
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)
这篇关于Django:limit_choices_to(这是正确的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!