2016-09-20 36 views
-1

我正在使用django項目中的註冊模塊。用於註冊用戶,我使用AUTH_USER表擴展這個表我創建一個多個模型簡介使用django中的一個查詢將數據保存在關聯模型中

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) 

資料表已成功創建。現在我想要做的是當我提交註冊表單時,在插入與auth_user模型相關的字段後,應該自動插入與註冊表單中的配置文件模型相關的字段。 意思是我不想先在auth_user模型中插入數據,然後在得到它的id後再次在Profile表中插入數據。 我想在一個查詢中插入完整的記錄。可能嗎 ?

+0

不可以。爲什麼你關心它是一個查詢還是兩個? –

+0

我是Php開發者,但是我必須在django中執行這個項目,在php的Cakephp框架中,我們只需使用一個查詢就可以在關聯表中插入記錄,從而使代碼更加乾淨和簡單。 – Pankaj

回答

0

我認爲你可以定義一個註冊表格並覆蓋save方法來創建用戶模型時保存Profile。示例代碼供您參考:

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 
+0

只是爲了記錄,這是兩個查詢。 – e4c5

相關問題