I have a Django project with two models: Applicant and Client, where Client is a subclass of Applicant. I would like some way of allowing a user to add an existing Applicant instance as a Client. I already have a view for Applicant instances, so I thought that having a Client model form on that page would do this, but from the documentation it does not look like you can initialize a model form with an instance of a superclass. I know I could do this by having code that goes directly to the database and adds a field to the subclass table, but is there a more Django-y way of doing it?
Asked
Active
Viewed 1,068 times
1 Answers
10
You can create a Client
instance from an existing Applicant
instance with the following code:
client = Client(applicant_ptr=applicant)
client.save_base(raw=True)

dgel
- 16,352
- 8
- 58
- 75
-
The code is [here](https://github.com/django/django/blob/master/django/db/models/base.py#L486). Basically it does what you want- it forces django to create the correct record in the subclass's table without creating a new `Applicant`. – dgel May 17 '12 at 18:40
-
I recommend you to have a look at this answer: http://stackoverflow.com/questions/9821935/django-model-inheritance-create-a-subclass-using-existing-super-class because you miss the client.__dict__.update(applicant.__dict__) Some of the filled in fields might be lossed if you forget this. – michel.iamit May 30 '12 at 20:39
-
1@michel.iamit, the `__dict__.update(applicant.__dict__)` hack is not necessary for this technique- that's why I use it. – dgel May 31 '12 at 16:43