oro*_*aki 22 django foreign-keys django-models
它是否正确?
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'})
Run Code Online (Sandbox Code Playgroud)
我正在努力确保订单表单只显示与订单属于同一帐户的客户选择.
如果我忽略了一些明显不好的设计谬误,请告诉我.
我最关心的是:
limit_choices_to={'account': 'self.account'}
Run Code Online (Sandbox Code Playgroud)
Dan*_*man 16
"它是否正确"的唯一答案是"运行时它是否有效?" 答案当然是否定的,所以我不知道你为什么要问这里.
根据当前模型中另一个字段的值,无法动态使用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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12634 次 |
| 最近记录: |