【问题标题】:Save model with OneToOne field使用 OneToOne 字段保存模型
【发布时间】:2013-10-11 13:00:56
【问题描述】:

我创建了一个配置文件模型来扩展默认 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)  

这是我的芹菜任务,它从 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'

有人知道我做错了什么吗?

【问题讨论】:

    标签: python django django-models django-users


    【解决方案1】:

    我在您的代码中发现了 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 建立具有一对一数据库连接的用户配置文件。

    希望这会有所帮助。

    【讨论】:

    • 太棒了!我在我的问题中忘记了 max_length,但在我的代码中却没有。
    • 我不知道,但它看起来很奇怪,因为没有这个参数你不能运行 django 服务器(模型验证会失败)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多