首页 > 解决方案 > 向用户模型添加多个信号会在 forst 表中创建记录,但不会在第二个表中创建记录

问题描述

我正在使用标准的 django.contrib.auth.models 用户模型,并将其扩展为创建一个与用户具有一对一关系的配置文件模型来保存个人资料图片。这个信号工作正常。从那以后,我添加了另一个模型,角色,它需要用户的常规外键,因为用户可以拥有多个角色。后者无论我如何尝试配置它都会给出一致的错误,包括为字段提供不同的related_name,以防混淆哪个是哪个以及具有与Profile而不是User的关系的角色模型,但无论我如何处理它,我无法让信号工作。

相关models.py文件代码如下:

模型.py:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    ...

class Role(TimeStampedModel):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    role = models.IntegerField('Roles',choices=Roles.choices, default=0)
   ...

信号.py:

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from core.models import Profile, Role

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

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

我得到的调试错误如下:

AttributeError at /login/
'User' object has no attribute 'role'
Request Method: POST
Request URL:    http://127.0.0.1:8000/login/
Django Version: 3.0.8
Exception Type: AttributeError
Exception Value:    
'User' object has no attribute 'role'
Exception Location: C:\project\path\core\signals.py in save_profile, line 15

I expect it's something to do with setting up a separate signal rather than having them in the same def but haven't been able to crack it after trying numerous ways. Likely just a silly thing I'm missing and will be grateful for a nudge in the right direction.

Thanks for taking a look.

Simon

标签: pythondjangodjango-models

解决方案


user have not role but roles, is the default related name in foreignkey you can change this by foreignkey(... , related_name="your_name")

so you can't do this for 2 reason

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

instance not have role but roles

instance.roles is not object but a queryset/list of role models


推荐阅读