2017-04-20 44 views
0

我刚从Django开始,只经历了初学者的文档。我正在尝试以下。在django中,为什么调用save()会清除父表中的数据?

models.py

from django.db import models 
from django.contrib.auth.models import User 
from django.db.models.signals import post_save 
from django.dispatch import receiver 
from org.models import Organization 

# Create your models here. 

class Profile(models.Model): 
    user = models.OneToOneField(User, on_delete=models.CASCADE) 
    organization = models.ForeignKey(Organization, null=True) 

@receiver(post_save, sender=User) 
def create_user_profile(sender, instance, created, **kwargs): 
    if created: 
     Profile.objects.create(user=instance) 

@receiver(post_save, sender=User) 
def save_user_profile(sender, instance, **kwargs): 
    instance.profile.save() 

当我创建一个用户,代码工作正常。行被添加到auth_user表和'profile'表中。在创建用户时,我不会将组织关联到用户。 'profile'表中的organization_id保持为NULL。

mysql> select * from user_profile; 
+----+---------------+---------+ 
| id | organization_id | user_id | 
+----+---------------+---------+ 
| 2 |   NULL |  3 | 
+----+---------------+---------+ 

后来我将用户关联到组织。我有以下代码。

views.py

... 
def user_association_done(request): 
    organization_id = request.POST['organization_id'] 
    user_id = request.POST['user_id'] 
    organization = Organization(id=organization_id) 
    user = User(id=user_id) 
    user.profile.organization = organization 
    user.save() 
    return HttpResponse('Done') 
... 

上面的代码组织到用户相关联(在配置表项被更新来填充的organization_ID),

mysql> select * from user_profile; 
+----+---------------+---------+ 
| id | organization_id | user_id | 
+----+---------------+---------+ 
| 2 |    1 |  3 | 
+----+---------------+---------+ 

但该行的数据在auth_user表中得到空白

mysql> select id, password, username from auth_user where id=3; 
+----+----------+----------+ 
| id | password | username | 
+----+----------+----------+ 
| 3 |   |   | 
+----+----------+----------+ 
1 row in set (0.00 sec) 

该行本身仍然存在。显然,我没有这样做,也许save()的调用不是正确的。

  1. 什么是正确的方法?
  2. 我很好奇,为什么/如何得到的数据从父表(在这种情况下AUTH_USER)
+0

如果您在创建对象之后正在处理引用,保存之前或者使用'User.objects.create()'而不是'User()'。基本上你在创建配置文件之前访问'.profile'。 –

回答

1

代替User(id=user_id)Organization(id=organization_id)削除,做

User.objects.get(id=user_id) 
Organization.objects.get(id=organization_id) 
+0

我想我正在创建新的对象,而不是提取现有的对象。 – user2125853

1
Try this function, 
def user_association_done(request): 
    organization_id = request.POST['organization_id'] 
    user_id = request.POST['user_id'] 
    organization = Organization.objects.get(id=organization_id) 
    user = user.objects.create(id=user_id,organization=organization) 
    user.save() 
    return HttpResponse('Done') 
相关问题