I have a model called Team
, with a ForeignKey relationship to Agent
(my user model). When an Agent who is a team_leader
deactivates the team, all the Agents with team_member
set to the current team will have their team_member
attribute removed and set to NULL/empty.
I read this and this, I know I'm either supposed to do something with ._meta.get_fields()
or with the Collector
class. I'm experimenting with the get_fields()
but haven't managed to get it working.
models.py
class Agent(AbstractUser):
team_member = models.ForeignKey('AgentTeam', on_delete=models.CASCADE, null=True, blank=True, related_name='team_member')
team_leader = models.OneToOneField('AgentTeam', on_delete=models.CASCADE, null=True, blank=True, related_name='team_leader')
class AgentTeam(models.Model):
team_is_active = models.BooleanField(default=False)
views.py
def deactivate_team(request):
request.user.AgentTeam.team_is_active = False # request.user in this case is the team_leader
# I need to set all the Agent's with team_member set to the request.user's team to NULL. I have experimented with the code below and gotten only errors, mostly related to ReverseToOne like ''ReverseManyToOneDescriptor' object is not iterable'
agents = [
f for f in AgentTeam._meta.get_fields()
if (f.one_to_many)
and f.auto_created and not f.concrete
]
for agent in agents:
objects = getattr(AgentTeam, agent.name).all()
for object in objects:
object.team_member = None
Please provide some comments and pointers on my views code and any errors I made. Thank you.