Reputation: 25
I have defined two OneToOneFields in my model as below:
class StudentCrossMap(models.Model):
rfId = models.OneToOneField(StudentDailyTrans)
studentId = models.OneToOneField(StudentMaster)
When I apply delete on the model above giving rfId
, the entry related to it in StudentDailyTrans
gets deleted, BUT the one in StudentMaster
did not gets removed.
Ideally, if I am deleting the object from StudentCrossMap
it should not be deleting the entries from mapped tables as those tables are not dependent on StudentCrossMap
table.
Please advise if I am doing something wrong.
*Edit: Related tables
class StudentDailyTrans(models.Model):
rfId = models.CharField(max_length=30, primary_key=True)
schoolId = models.ForeignKey(SchoolMaster, on_delete=models.CASCADE, db_index=False)
fromTime = models.DateTimeField(null=True)
toTime = models.DateTimeField(null=True)
totalSwipeInstance = models.IntegerField(default=0)
lastUpdateTs = models.DateTimeField(auto_now=True)
class StudentMaster(models.Model):
studentId = models.IntegerField(primary_key=True)
schoolId = models.ForeignKey(SchoolMaster, on_delete=models.CASCADE)
parentId = models.ForeignKey(ParentMaster, on_delete=models.CASCADE)
class SchoolMaster(models.Model):
schoolId = models.IntegerField(primary_key=True)
subsStrtDt = models.DateTimeField(default=timezone.now)
class ParentMaster(models.Model):
parentId = models.AutoField(primary_key=True)
parentName = models.CharField(max_length=20, default='parent')
Upvotes: 1
Views: 121
Reputation: 53774
If I have understood what you have posted correctly, you are better off with a design like this.
class Student(models.Model):
id = models.IntegerField(primary_key=True)
school = models.ForeignKey(SchoolMaster, on_delete=models.CASCADE)
parent = models.ForeignKey(ParentMaster, on_delete=models.CASCADE)
rf = models.CharField(max_length=30, primary_key=True)
This is essentially, your old StudentMaster
model. I have renamed it to Student. I have also renamed the field names to comply with the usual django naming convention (school instead of school_id for the foreign key)
Now you can delete StudentDailyTrans
and StudentCrossMap
we are saving the same data more efficiently and yet without redundancy. And that eliminates the problem you asked about!!
You will agree with me that the code is a lot more readable.
Upvotes: 2