更新用户模型并保存新模型 - Django

时间:2017-06-19 13:36:22

标签: django

我尝试使用ForeignKey模型作为RecursionError: maximum recursion depth exceeded来保存模型,但是当我尝试保存模型时,我得到from django.db import models from django.contrib.auth.models import (User, Group) from phonenumber_field.modelfields import PhoneNumberField class AuthenticatorModel(models.Model): id = models.IntegerField(auto_created=True, default=1, primary_key=True, serialize=False) user_id = models.ForeignKey(User, related_name='auth_user', null=True) first_name = models.CharField(default='First Name', max_length=50) last_name = models.CharField(default='Last Name', max_length=50) phone_number = PhoneNumberField() email_id = models.CharField(default='email ID', help_text='Enter the email ID used to register the Django user', max_length=50) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): try: obj = User.objects.get(id=self.id) obj2 = AuthenticatorModel.objects.get_or_create(id=self.id) except User.DoesNotExist: return obj.first_name = self.first_name obj.last_name = self.last_name obj2.phone_number = self.phone_number obj.email = self.email_id obj.save() return super(AuthenticatorModel, self).save()

我的代码是:

AuthenticatorModel

我不确定这是错的。如何为first_name创建内容并更新last_nameemailtextfield = CreateWindow(L"STATIC", L"HELLO", WS_VISIBLE | WS_CHILD | WS_BORDER, 300, 300, 100, 25, hWnd, (HMENU)1, hInstance, NULL);

1 个答案:

答案 0 :(得分:2)

You are manually calling get_or_create() in the save() method, but get_or_create() itself is also calling save(). There is no need to create obj2, since you are calling the super method at the end.

You could just do this:

def save(...):
    try:
        obj = User.objects.get(id=self.id)
   except User.DoesNotExist:
        return

    obj.first_name = self.first_name
    obj.last_name = self.last_name
    obj.email = self.email_id
    obj.save()

    return super(AuthenticatorModel, self).save()