'DRF Error: Cannot assign must be a instance
I'm working on an app that lets you track your expenses and I'm trying to create an 'balnace' object when the user registers, but when I try so I get an Error: Cannot assign "15": "Balance.user_id" must be a "Users" instance.
Model
class Balance(models.Model):
balance = models.FloatField(
verbose_name="Balance", blank=False, null=False)
user_id = models.ForeignKey(
'expenseApi.Users', verbose_name="Usuario", blank=False, null=False, on_delete=models.PROTECT)
def __str__(self):
return '{}'.format(self.pk)
serializer
class RegisterSerializer(serializers.ModelSerializer):
tokens = serializers.SerializerMethodField()
email = serializers.EmailField(max_length=50)
class Meta:
model = Users
fields= ['id', 'email', 'password', 'name', 'lastname', 'birthday', 'tokens']
extra_kwargs = {
'password': {
'write_only': True,
},
}
def get_tokens(self,user):
refresh = RefreshToken.for_user(user)
data = {
'refresh': str(refresh),
'access': str(refresh.access_token),
}
return data
def create(self, request):
email= Users.objects.filter(email=request['email'])
if email:
raise serializers.ValidationError({'detail': 'El email ya esta en uso'})
user = Users.objects.create_user(email=request['email'],
password=request['password'],
name=request['name'],
lastname=request['lastname'],
birthday=request['birthday'])
user['balance'] = Balance.objects.create(balance=0,user_id=user.id)
return user
Solution 1:[1]
I didn't go in detail about logic on your code but I guess error based on your code at
user['balance'] = Balance.objects.create(balance=0,user_id=user.id)
should be
user['balance'] = Balance.objects.create(balance=0, user_id=user)
Solution 2:[2]
Since you named your ForeignKey
user_id
, this means that you can assign a User
object to .user_id
, or the primary key to .user_id_id
:
user['balance'] = Balance.objects.create(
balance=0,
user_id_id = user.id
)
I would however advise to rename user_id
to user
, since now the field "hints" that it is an id, but it is not.
class Balance(models.Model):
balance = models.FloatField(verbose_name='Balance')
user = models.ForeignKey(
'expenseApi.Users',
verbose_name='Usuario',
on_delete=models.PROTECT
)
# …
Then we thus can set this with:
user['balance'] = Balance.objects.create(
balance=0,
user_id = user.id
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | webbyfox |
Solution 2 | Willem Van Onsem |