我有这个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添加数据
1条答案
按热度按时间qxgroojn1#
保存
user
字段时未添加外键的用户对象,这是一个错误您可以在保存()方法中传递user对象,如下所示...