django 我有两个相互关联的Model,我希望在ModelA中创建数据时自动在ModelB中创建数据

vptzau2j  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(132)

我有这个User模型,它来自Django Admin的用户

class NewUser(AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(_('email address'), unique=True)
    user_name = models.CharField(max_length=150, unique=True)
    first_name = models.CharField(max_length=150)
    start_date = models.DateTimeField(default=timezone.now)
    is_staff = models.BooleanField(default=True)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

    objects = CustomAccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['user_name', 'first_name']

    def __str__(self):
        return str(self.id) + " " + self.email

我还有一个与User模型相关的模型,称为Promoter模型

class Promoter(models.Model):
    user = models.ForeignKey(
        NewUser,
        on_delete=models.CASCADE,
    )

    def __str__(self):
        return str(self.user.id) + " " + self.user.email

    def email(self):
        return self.user.email

每次我向User中添加数据时,我都想自动向Promoter模型中添加一个数据,并链接到新创建的User
这是我添加/注册新用户的代码

class RegisterView(APIView):
    permission_classes = [AllowAny]

    def post(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            newuser = serializer.save()
           

            if newuser:
                return Response(status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我尝试手动将新创建的User添加到前端,方法是使用两个不同的API调用来添加用户和推广者,但在手动添加推广者数据(1048, "Column 'user_id' cannot be null")时出现错误
我还尝试使用postman x1c 0d1x添加数据

qxgroojn

qxgroojn1#

保存user字段时未添加外键的用户对象,这是一个错误
您可以在保存()方法中传递user对象,如下所示...

def post(self, request):
    serializer = UserSerializer(data=request.data)
    if serializer.is_valid():
        newuser = serializer.save(user=request.user)

相关问题