Django信号为同一模型创建

时间:2017-12-05 15:31:32

标签: django

我正在尝试根据CustomUser的类型创建一个创建Client对象或Director对象的信号:

class CustomUser(AbstractEmailUser):
    TYPE = (
        (0, 'Client'),
        (1, 'Director'),

    type = models.PositiveSmallIntegerField(default=0, choices=TYPE)


class Client(models.Model):
    user = models.OneToOneField(CustomUser)


class Director(models.Model):
    user = models.OneToOneField(CustomUser)


def post_save_data(sender, instance, created, **kwargs):
    if created and CustomUser.objects.get(email=instance.email).type == 0:
        Client.objects.create(user=instance)
    elif created and CustomUser.objects.get(email=instance.email).type == 1:
        Director.objects.create(user=instance)


post_save.connect(post_save_data, sender=CustomUser)

无论我做什么,它总是为客户创建对象,即使我选择类型1。

1 个答案:

答案 0 :(得分:0)

我正在使用以下代码,如果我通过选择客户端创建自定义用户,则使用django admin,如果选择Director,则会创建Director。

class AbstractEmailUser(models.Model):
    email = models.TextField(max_length=100)


class CustomUser(AbstractEmailUser):
    TYPE = (
        (0, 'Client'),
        (1, 'Director'),
    )

    type = models.PositiveSmallIntegerField(default=0, choices=TYPE)


class Client(models.Model):
    user = models.OneToOneField(CustomUser)


class Director(models.Model):
    user = models.OneToOneField(CustomUser)


def post_save_data(sender, instance, created, **kwargs):
    # if created and CustomUser.objects.get(email=instance.email).type == 0:
    #     Client.objects.create(user=instance)
    # elif created and CustomUser.objects.get(email=instance.email).type == 1:
    #     Director.objects.create(user=instance)
    if created:
        c_user = CustomUser.objects.get(email=instance.email)
        print(c_user.type)
        if c_user.type == 0:          
            Client.objects.create(user=instance)
        elif c_user.type == 1:
            Director.objects.create(user=instance)


post_save.connect(post_save_data, sender=CustomUser)

post_save_data上面评论的代码也对我有用。我使用AbstractEmailUser类作为样本。