I have a FieldOfficer model, which has region, team_leader and other attributes.
first_name = models.CharField(max_length=30, blank=False, null=False)
last_name = models.CharField(max_length=30, blank=False, null=False)
team_leader = models.ForeignKey('TeamLead', on_delete=models.SET_NULL, null=True,
region = models.CharField(max_length=30, blank=False, null=False)
Additionally, TeamLead and Agent are proxies of the above module.
A TeamLead has many agents, but an agent has one teamlead. An agent should belong to the same region as his TeamLeader.
Upon edit or creation of an agent, i want to enforce the above. ie when i select a teamlead, the agent’s region be the region of the selected team leader. I also want to validate this constraint.
How do i proceed, am using model forms and ModelChoiceField to list all Teamleads available for selection when creating/Updating?
@KenWhitesell already edited, please help
Assuming the “base case” that this is just a two-tier environment, my first reaction is to ask why you’re storing the region at all for the Agent. If this is an absolute constraint (an Agent’s region must always be the same as the TeamLead), then there’s no reason to store it as an attribute of Agent.
Beyond that, I wouldn’t make region a field on the form. I’d set it as a value in the view when it’s being saved. (You can think of it as being analogous to the situation of saving the current user as shown in the example in The save method.) You could also make it more “global” by setting it in the
save method for the model.
Side note: Please don’t tag specific individuals requesting assistance. We are all volunteers here contributing information as time, energy, and knowledge allows.
Should region be a table on its own with a one to one relation with the FieldOfficer? also thanks for the reply, the side note is well noted
This depends upon whether or not the only difference in fields between a TeamLead and an Agent is the region. (Well, I guess another difference is that the team_leader field is Null for a TeamLead.)
IF the difference between a TeamLead and Agent are only those two elements, and IF there’s only one TeamLead for a region, then yes, you could simplify this by creating a table for Region having a 1-1 with a TeamLead.
The difference between a teamlead and Agent is just behavioral. I use them as proxy models.