Save data in associative model using one query in django
<p>I am working on registration module in django project. for registering user i am using auth_user table for extending this table i have created one more model Profile</p>

<pre><code>from django.contrib.auth.models import User
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    start_date = models.DateField()
    phone_number = models.CharField(max_length=12)
    address = models.CharField(max_length=225)
    subscription = models.BooleanField(default=False)
</code></pre>

<p>Profile table has been created successfully. Now what i want to do is when i submit the registration form, the fields related to Profile model within registration form should be inserted automatically after inserting fields related to auth_user model.
Means i don't want to first insert data in auth_user model and then after getting it's id again insert data in Profile table.
I want to insert complete record in one query. Is it possible ?</p>

<p>I think you can define a registration form and override the form <code>save</code> method to save the <code>Profile</code> when creating the User model. Sample code for your reference:</p>

<pre><code>class RegistrationForm(forms.ModelForm):
    start_date = forms.DateField()
    phone_number = forms.CharField()
    address = forms.CharField()
    subscription = forms.BooleanField()

    class Meta:
        model = User

    def save(self, commit=True):
        instance = super(RegistrationForm, self).save(commit=commit)
        profile = Profile(user=instance, start_date=self.cleaned_data['start_date'], phone_number=self.cleaned_data['phone_number'], address=self.cleaned_data['address'], subscription=self.cleaned_data['subscription'])
        profile.save()
        return instance


def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
             user = form.save()
             # do anything after user created
        else:
             raise Error('form validate failed')
    else:
         # handling the GET method
</code></pre>

python django database