Home > database >  How to automatically update a field when creating another record in different models?
How to automatically update a field when creating another record in different models?

Time:10-21

I have two models that look like this:

class TeamMember(models.Model):
    member = models.ForeignKey(User, on_delete=models.SET(get_default_team_member), 
                verbose_name='Member Name', related_name="team_members")
    team = models.ManyToManyField('Team', verbose_name='Team Name', 
            related_name="team_members", blank=False, default=team_id)
    shift = models.ForeignKey(Shift, on_delete=models.PROTECT)
... 
class Team(models.Model):
    name = models.CharField(max_length=50)
    members = models.ManyToManyField(TeamMember, blank=True, related_name="members")

`

The users use the admin panel to add new members. When adding a new member, I want to automatically add the member to the associated team.

For example, when adding John, it is required to assign a team to him(blank=False), and the team is from what we have in the Team model. Then how do I update the members in the Team model to add John to one of the teams accordingly?

Please help, thanks!

CodePudding user response:

You can do as like this 
form = TeamMemberForm()
if form.is_valid():
    instance = form.save()
    team = Team.objects.create(name="John")
    instance.members.add(team)

CodePudding user response:

class MyModel(models.Model):
    name = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(blank=True, unique=True)
    is_activate = models.BooleanField(default=True)

    def __str__(self):
        return f'{self.name} {self.product_name}'

    def create_auto_slug(self):
        self.slug = slugify(f'{self.name}-{self.pk}')

    def model2save(self):
        MyModel2.objects.create(**your_data)

    def save(self, *args, **kwargs):
        model2save()
        super(Product, self).save(*args, **kwargs)
        self.create_auto_slug()

other method - signals

  • Related