dealing with foreign keys in Django

Issue

i am creating a doctor appointment system, and i did include prescriptions too

class Prescription(models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    doctor = models.ForeignKey(Doctor, null = True, on_delete=models.SET_NULL)
    clinic = models.ForeignKey(Clinic, on_delete=models.SET_NULL)

i was thinking what if the doctor delete his account for some reasons, can the doctor or the clinic set to null if this happen?

Solution

You can add doctor_name and clinic_name fields in your models.py:

class Prescription(models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    doctor = models.ForeignKey(Doctor, null = True, on_delete=models.SET_NULL)
    clinic = models.ForeignKey(Clinic, on_delete=models.SET_NULL)

    doctor_name = models.CharField(max_length=100, blank=False)
    clinic_name = models.CharField(max_length=100, blank=False)

And add the doctor’s name and the name of the clinic each time. However, this is very redundant….

Actually, here iss stackoverflow’s database schema -> url.
As you can see, there’s OwnerDisplayName so that posts still have author’s name.

Answered By – bichanna

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published