26

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'}
orokusaki
  • 55,146
  • 59
  • 179
  • 257

3 Answers3

24

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
  • 588,541
  • 66
  • 880
  • 895
  • 55
    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 Dec 28 '09 at 17:24
  • This is also good if you need to have request obj in class MyOrderForm -> http://stackoverflow.com/a/6062628/758202 – zzart Mar 07 '13 at 09:15
  • 1
    Yes, this is not very clear in the docs. I suppose the problem is that `limit_choices_to` is a parameter of the ForeignKey function, and that function must be assigned to a class member. At this level, `self` means nothing. To make it working, `Django` should have a filter function that works in `__init__`, and, for what I know, it hasn't one. – Marco Sulla Nov 16 '14 at 16:54
0

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

Antony Hatchkins
  • 31,947
  • 10
  • 111
  • 111
-2

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

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
Mayuresh
  • 1,062
  • 9
  • 10