dimanche 13 juin 2021

Flow of creation of related models through a foreign key

I have been searching and reading some documentations, but I have not found information about best practices in the backend for the creation of two related models through a foreign key. I´ll explain myself:

If I have a main model called User, and a User related model called Student, what would be the best approach to create the Student model??

  • What to do in case one of them becomes invalid during the creation process?
  • Should I delete the User object if there are any errors during the creation of the Student object?
  • What would be the flow diagram in the .save() method in Student model?

I will provide some code in Django, but my question is not language-specific.

class Student(models.Model):
    user = models.ForeignKey(User, default=None)
    name = models.CharField(max_length=32, unique=True)
    school = models.CharField(max_length=32)
    califications = models.CharField(max_length=32)

class User(models.Model):
    name = models.CharField(max_length=32, unique=True)
    mother_name = models.CharField(max_length=32)
    father_name = models.CharField(max_length=32)
    age = models.IntegerField()

Aucun commentaire:

Enregistrer un commentaire