2

is it possible to create an object using another object which model has the same attributes?

In my case, I have two models - TemporaryJob and Job. The TemporaryJob is created when user fills the form. Next thing is to confirm. If he confirms TemporaryJob, the object should be converted to regular Job object.

class Job(models.Model):
    attributes
    methods

class TemporaryJob(Job):
    pass

I've tried Job.objects.create(temporary_job_instance) but it does not work.

Milano
  • 18,048
  • 37
  • 153
  • 353

2 Answers2

8

This is what I do. Could be bad if you save your temporary_job_instance, so just don't.

a_dict = temporary_job_instance.__dict__
del a_dict['_state']
del a_dict['id']
Job.objects.create(**a_dict)
Jason Mads
  • 81
  • 1
  • 3
5

First of all, Klaus D. comment is correct: I also don't think that your design is correct. Instead of having Job and TemporaryJob models with similar fields you should only have a Job model that has a boolean is_temporary field that would be True of this is a temporary job or False if not. If you go this way then you wouldn't need to copy the values between tables. All other problems you'll experience will be resolved more easily if you have normalized data.

In any case, to actually answer your question, notice that objects.create() is using kwargs (i.e it should be called like Job.objects.create(attr1=val1, att2=val2) etc. The best way to output these kwargs is to create a dictionary with the values of the object you want to pass (the values of temporary_job_instance) and pass it to create using the unpacking syntax (**). So, if values is a dictionary with the values of temporary_job_instance, you could just call Job.objects.create(**values).

Now you just need to create the values dict from your temporary_job_instance. Unfortunately, there's no easy way to do that in django :( It can be done though -- you can take a look at theses questions for some insight and a lot of methods of doing it: Convert Django Model object to dict with all of the fields intact or this Django: Converting an entire set of a Model's objects into a single dictionary

Community
  • 1
  • 1
Serafeim
  • 14,962
  • 14
  • 91
  • 133