jonco91
jonco91

Reputation: 95

Limit Choices to Foreign Key based on lookups that span relationships

This is what I have so far.

models.py

class Company(models.Model):
    company_name = models.CharField('Company', max_length=40, unique=True)
    company_type = models.CharField('Type', max_length=20, null=True, blank=True)

class MyUser(AbstractBaseUser):
    email = models.EmailField(max_length=80, unique=True)
    first_name = models.CharField('First Name', max_length=25)
    last_name = models.CharField('Last Name', max_length=25)
    company = models.ForeignKey(Company,limit_choices_to *********

class Organization(models.Model):
    owner = models.ForeignKey(Company, null=True, related_name='owner')
    client = models.ForeignKey(Company, null=True, related_name='client')

I would like the current user (the one that is logged in) to create Users for companies that are clients of his/her company.

So, my guess is

MyCompany = request.user.company
company = models.ForeignKey(Company, limit_choices_to=(Organization__owner="MyCompany"))

Any help is greatly appreciated. Thanks in Advance.

Upvotes: 1

Views: 48

Answers (1)

Glyn Jackson
Glyn Jackson

Reputation: 8354

There is no way to define it dynamically on the database level using limit_choices_to. You simply need to define it on your form/view etc. i.e Use a modelchoicefield.

Upvotes: 1

Related Questions