Django trigger add on models

Question:

In adminsite, I want if the user create an account on Student table, it will also add to the dashboard table, how can i do that?

class Dashboard(models.Model):
    fullname = models.CharField(max_length=50,blank=True, null=True)
    status = models.CharField(max_length=50,blank=True, null=True)
    dateCreated = models.DateTimeField(default=datetime.now())


class Student(models.Model):
    Gender = [
        ('Male', 'Male'),
        ('Female', 'Female')
    ]
    fullname = models.CharField(max_length=50, null=True)
    status = models.CharField(max_length=500,  null=True, default='Student')
    contact_number = models.IntegerField(max_length=50,   null=True)
    age = models.IntegerField( null=True)
    gender = models.CharField(max_length=50, choices=Gender,  null=True)
    birthdate = models.DateField(max_length=50,  null=True)
    class Meta:
        verbose_name_plural = "LIST OF STUDENTS"
Asked By: Claire Ann Vargas

||

Answers:

You could overwrite the save method of class Student like e.g. so:

class Student(models.Model):
    Gender = [
        ('Male', 'Male'),
        ('Female', 'Female')
    ]
    fullname = models.CharField(max_length=50, null=True)
    status = models.CharField(max_length=500,  null=True, default='Student')
    contact_number = models.IntegerField(max_length=50,   null=True)
    age = models.IntegerField( null=True)
    gender = models.CharField(max_length=50, choices=Gender,  null=True)
    birthdate = models.DateField(max_length=50,  null=True)
    class Meta:
        verbose_name_plural = "LIST OF STUDENTS"

     def save(self, *args, **kwargs):

        # Create a new Dashboard instance
        Dashboard.objects.get_or_create(
            fullname=args,  # Pass your desired values to the save method
            status=args  # Pass your desired values to the save method
        )
        print('New Student and Dashboard instance created')
        # Run save method on Student instance
        super(Student, self).save(*args, **kwargs)

Note that get_or_create could be replaced with any other creation approach of a new dashboard approach. Now whenever you create and save a student instance the code inside its save method is executed accordingly.

Answered By: JSRB

You can do it in many ways, I would suggest you to use signals, Django provides us with post_save signal. The signals helps us to have a clearer and decoupled implementation.

Your student class will remain as it is

class Student:
    <...attributes_here...>

you can create a listeners.py and define a listener for Student save action

@receiver(post_save, sender=Student)
def create_dashboard_on_student_save(sender, instance, created, **kwargs):
    # note - you have the student instance here, you can use it's values

    if not created:
        return

    Dashboard.objects.get_or_create(
        fullname=<value>,
        status=<value>
    )

Please use this as ref: https://docs.djangoproject.com/en/4.1/topics/signals/ to implement signals.

Answered By: Vikrant Srivastava

I think the best way of implement this is using signals. In this case use post_save method.

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Student)
def create_dashboard_profile(sender, instance, created, **kwargs):
    if created:
      Dashboard.objects.create(fullname=instance, status=instance)
    else:
      pass

I recommend read this article. It helped me to understand better how signals work.

Answered By: ZapSys
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.