views:

253

answers:

3

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'}
A: 

limit_choices_to={'account': 'self.account'} is wrong, since foreign key to customer cannot point to Account.

Mayuresh
Customer has "account" attribute though. Still this is the case?
orokusaki
A: 

You should set choices field of your order form (inherited from ModelForm) in the constructor.

Antony Hatchkins
+1  A: 

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)
Daniel Roseman
Just because it didn't work for me didn't mean it had to be the wrong approach. I asked because there isn't clear documentation about this feature on the Django site, and I wasn't sure if my syntax was correct.
orokusaki