Django:limit_choices_to(这是正确的) [英] Django: limit_choices_to (Is this correct)

查看:711
本文介绍了Django:limit_choices_to(这是正确的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类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'}


解决方案

这是正确的是它运作时,它运行吗?答案当然是不,所以我不知道你为什么问这里。

  • 无法动态地使用limit_choices_to mit基于当前模型中另一个字段的值。最好的方法是通过自定义表单。定义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)


    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屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆