如果父模型不存在,则仅从可见字段更新

时间:2015-02-16 14:45:50

标签: django django-models django-forms

我有继承自User的django模型:

models.py

class UserProfile(User):
  birth_date = models.DateField()
  bio = models.TextField(null=True)
  ...

forms.py

class UserProfileForm(forms.ModelForm):
  birth_date = forms.DateField()
  class Meta:
    model = UserProfile
    fields = ('first_name', 'last_name', 'birth_date', 'bio')

所以我在数据库中有2个表:

  • auth_user(id,username,first_name,last_name,...)
  • user_profile(birth_date,bio,user_ptr_id) 与one to one关系。

我需要更新或创建(如果它们不存在)只有我的表单中指定的原始数据。使用SQL的情况如下:

UPDATE auth_user 
SET first_name=form_first_name, last_name=form_last_name
WHERE id = request.user.id

IF EXISTS (SELECT * FROM user_profile WHERE user_ptr_id = request.id)
  UPDATE user_profile 
  SET (birth_date = form_birth_date, bio = form_bio)
  WHERE user_ptr_id=request.id
ELSE
  INSERT INTO user_profile (user_ptr_id, birth_date, bio)
  VALUES (request.user.id, form_birth_date, form_bio )

理论上应该是这样的:

user_profile = UserProfile.objects.get(pk=request.user.id)
form = UserProfileForm(request.POST, instance=user_profile)

但如果数据库中没有原始内容,它会抛出异常。有没有办法来完成它?或者我只需要做多次检查?

1 个答案:

答案 0 :(得分:1)

如果我找对你,你应该使用get_or_create(see docu

user_profile = UserProfile.objects.get_or_create(pk=request.user.id)

此外,您需要派生自AbstractBaseUser而不是User。

class UserProfile(AbstractBaseUser):
       birth_date = models.DateField()
       ....

请参阅Specifying a custom User model的文档。