What I have:
The default django User model with an attached Profile model that, amongst others, contains a ForeignKey to an Office model. So every user in my application is tied to a specific office. And in each office there are several Shifts.
models.py:
class Profile(models.Model):
id = models.AutoField(primary_key=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
office = models.ForeignKey(Office, on_delete=models.RESTRICT)
class Office(models.Model):
id = models.AutoField(primary_key=True)
short_name = models.CharField(max_length=3, default='FRA', null=True, unique=True)
long_name = models.CharField(max_length=10, default='Frankfurt', null=True, unique=True)
class Shift(models.Model):
id = models.AutoField(primary_key=True)
office = models.ForeignKey(Office, on_delete=models.RESTRICT)
short_name = models.CharField(max_length=5, default="")
long_name = models.CharField(max_length=20, default="")
What I am trying to do:
Now, in my CreateView
I want to limit the available choices in the "shift" field to the ones attached to the office of the current logged in user. I thought about using the limit_choices_to
option of ForeignKey
, but I can't get my head around how to access the user information within a model? Something like
class Shift(models.Model):
id = models.AutoField(primary_key=True)
office = models.ForeignKey(Office, on_delete=models.RESTRICT, limit_choices_to={'office': ???})
short_name = models.CharField(max_length=5, default="")
long_name = models.CharField(max_length=20, default="")