I have two models:
class Group(models.Model):
name = models.CharField(max_length=50, null=False, blank=False)
class User(models.Model):
username = models.CharField(max_length=50, null=False, blank=False)
password = models.CharField(max_length=50, null=False, blank=False)
group = models.ForeignKey(Group, null=False, on_delete=models.CASCADE)
And I have serializers for both of them:
class GroupSerializer(serializers.Serializer):
name = serializers.CharField()
class UserSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
group = serializers.PrimaryKeyRelatedField(queryset=Group.objects.all())
Then in the registration view, I'm trying to automatically create a group when user is registering their account:
@api_view(['POST'])
def registration(request):
# Creates a new group
g_serializer = GroupSerializer(data=request.data, partial=True)
g_serializer.is_valid(raise_exception=True)
group = g_serializer.save()
# Creates a new user
u_serializer = UserSerializer(data=request.data, partial=True)
u_serializer.is_valid(raise_exception=True)
user = u_serializer.save()
As you can imagine the error I'm getting is that group
field for User class violates not null restriction.
I tried to fix it by doing u_serializer['group'] = group.id
or u_serializer['group'] = group
but it throws the following error:
TypeError: 'UserSerializer' object does not support item assignment
How can I handle this? The new Group object is being properly created and inserted into the db and I need to assign that object to user.group.