在django中,为什么调用save()会从父表中清除数据?

时间:2017-04-20 03:59:14

标签: python django

我开始使用django并且只通过了初学者和#39;文档。我正在尝试以下内容。

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'表。在用户创建时,我不将组织与用户关联。在'个人资料中的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)

2 个答案:

答案 0 :(得分:1)

而不是User(id=user_id)Organization(id=organization_id),请执行

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

答案 1 :(得分: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')