使用OneToOne字段保存模型

时间:2013-10-11 13:00:57

标签: python django django-models django-users

我创建了一个profile-model来扩展默认的django用户(使用django 1.6) 但我无法正确保存配置文件模型。

这是我的模特:

from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User)
    mobilephone = models.CharField(max_length=20, blank=True)  

这是我的celery-task,用于更新wdsl文件中的个人记录:

@task()
def update_local(user_id):

    url = 'http://webservice.domain.com/webservice/Person.cfc?wsdl'

    try:
        #Make SUDS.Client from WSDL url
        client = Client(url)
    except socket.error, exc: 
        raise update_local.retry(exc=exc)
    except BadStatusLine, exc:
        raise update_local.retry(exc=exc)


    #Make dict with parameters for WSDL query
    d = dict(CustomerId='xxx', Password='xxx', PersonId=user_id)

    try:
        #Get result from WSDL query
        result = client.service.GetPerson(**d)
    except (socket.error, WebFault), exc:
        raise update_local.retry(exc=exc)
    except BadStatusLine, exc:
        raise update_local.retry(exc=exc)



    #Soup the result
    soup = BeautifulSoup(result)


    #Firstname
    first_name = soup.personrecord.firstname.string

    #Lastname
    last_name = soup.personrecord.lastname.string

    #Email
    email = soup.personrecord.email.string

    #Mobilephone
    mobilephone = soup.personrecord.mobilephone.string



    #Get the user    
    django_user = User.objects.get(username__exact=user_id)

    #Update info to fields
    if first_name:
        django_user.first_name = first_name.encode("UTF-8")

    if last_name:    
        django_user.last_name = last_name.encode("UTF-8")

    if email:
        django_user.email = email


    django_user.save() 



    #Get the profile    
    profile_user = Profile.objects.get_or_create(user=django_user)

    if mobilephone:
        profile_user.mobilephone = mobilephone

    profile_user.save()

django_user.save()工作正常,但profile_user.save()无效。我收到此错误:AttributeError: 'tuple' object has no attribute 'mobilephone'

任何人都能看到我做错了什么?

1 个答案:

答案 0 :(得分:6)

我在你的代码中发现了2个错误:

  • get_or_create方法返回元组(对象,已创建),因此您必须将代码更改为:

    profile_user = Profile.objects.get_or_create(user=django_user)[0]

    或者,如果您需要有关返回对象状态的信息(刚创建或不创建),您应该使用

    profile_user, created = Profile.objects.get_or_create(user=django_user)

    然后其余代码将正常工作。

  • 在您的个人资料模型中,字段models.CharField必须声明max_length个参数。

  • 您无需在()装饰器中使用@task。如果将参数传递给装饰器,则只需执行此操作。

  • 此外,您可以使用django custom user model避免使用一对一数据库连接构建用户个人资料。

希望这有帮助。