django: Switch the inherited model base class to different child
The base class model and inherited models are as follow:
class Profile(models.Model):
user = models.ForeignKey(User, unique=True)
...
class Student(Profile):
...
class Teacher(Profile):
...
I have object of Student class(the data for which are stored in two tables in db - Profile table and a Student table which has a pointer to Profile table). I need to assign that Profile table row to a Teacher object and delete the Student object, i.e. without losing the content of Profile t开发者_运维问答able data and also retaining the same id for that row. How it should be done?
Thank you,
Any help would be appreciated..
Behind the scenes, Django creates a field on the Student and Teacher models called profile_ptr_id. So you'll probably have to manipulate that. Because of how Django's concrete inheritance works, each Student and Teacher object's primary key is actually this profile_ptr_id field. Thus, I am not sure having both a Student and Teacher object with the same profile_ptr_ids is allowed.
One way you can try to get around this is the following:
- Create a new Profile object
- Set the Student object's profile_ptr_id to the id of the new Profile object
- Set the Teacher object's profile_ptr_id to the id of the old Profile object that the Student object was previously pointing to.
- Delete the Student object
I've never tried this, so I really can't say if it will work or not...
If you have a student that you want to turn into a teacher with some or all fields, and you can afford to type out the fields, you can just do:
teacher = Teacher(id=student.id, user=student.user,
name=student.name, email=student.email, ...)
student.delete()
teacher.save()
It's important to set the ID and delete the old object before saving the new one with the same ID.
精彩评论