How to use user as foreign key

Hi all,

===========================================
I have a Deposit model class and the definition is as follows:

from django.db import models
from django.contrib.auth.models import User
from django_pandas.managers import DataFrameManager

class Deposit(models.Model):

deposit_id = models.AutoField(primary_key=True)
transaction_type = models.CharField(max_length=20)
amount = models.FloatField(null=False)
balance = models.FloatField(null=False)

user = models.ForeignKey(User, on_delete=models.CASCADE)

===========================================
When I add and save an instance of Deposit class, an error below occurred as follows:

from django.contrib.auth.models import User
from algo.models import Deposit

user = User.objects.create_user(‘test_account’, ‘test_account@hotmail.com’, ‘test_password’)
user.save()

user = User.objects.get(username=‘test_account’)
deposit = Deposit(user=user
, transaction_type=‘deposit’
, amount=2000000
, balance=2000000)

deposit.save()

ProgrammingError : column “user_id” of relation “algo_deposit” does not exist LINE 1: …eposit" (“transaction_type”, “amount”, “balance”, “user_id”)…

===========================================
It keeps saying that user_id is missing.
I kinda understand that it’s not a good idea to directly use User in model classes. But what if I need to use User as a foreign key? How should I do this?

Regards,
Kelvin

This issue is happening because you are not supplying a user instance when creating your deposit instance. There’s nothing wrong with using User in your model classes. In fact, Django is sometimes seen as an opinionated framework because a lot of the features built into it are assuming that you will need things such as user authorization and permissions, which use the User model.

If you go through the documentation on ForeignKey relationships, you will see that when creating an Article instance, they are supplying a Reporter instance. If they did not do this, they would receive an error similar to what you are seeing.

Hope this helps!

Side Note –

You do not need to add an AutoField to your model. Django will add this to every model you create by default :slight_smile:

Thanks for your reply.

Actually, I passed in a user instance while initializing a deposit instance.

In that case, is there any other reason causing user_id missing?

================================

from django.contrib.auth.models import User
from algo.models import Deposit

user = User.objects.create_user(‘test_account’, ‘test_account@hotmail.com’, ‘test_password’)
user.save()

user = User.objects.get(username=‘test_account’)
deposit = Deposit(user=user
, transaction_type=‘deposit’
, amount=2000000
, balance=2000000)

deposit.save()

================================

Would you mind printing out the result of user = User.objects.get(...)? Another reason could be that your query is returning None instead of a User instance. I doubt it, but it doesn’t hurt to try.

Is this a recent change where you’ve not yet done a makemigration / migrate?

It might be worth going into your database directly and verify that the table matches your model.

Also, when posting code, please enclose the code between lines consisting of three backtick - ` characters. This means you’ll have a line of ```, followed by your lines of code, then another line of ```. This will ensure that your code remains properly formatted. (This is really important with Python because of the significant white-space.)

Actually, that’s not quite an accurate interpretation of the message. It’s saying that the column named “user_id” doesn’t exist in the table in the database - a completely different issue.

The User model I used is the default User model.

The default User model does not have a column called ‘user_id’

It seems that when initializing a deposit instance, it looks for column ‘user_id’ instead of ‘id’ as foreign key by default.

If I’m not going to extend or make a custom user model, is there any way to handle it?

Regards,
Kelvin

Correct, the User model doesn’t have one - it doesn’t need one. It has a column named id.

It’s the Deposit model that has (or should have), in the database, a column named user_id.

If you don’t find a column named user_id in the database in your deposit table, then either you’ve forgotten to do a makemigration / migrate or you’ve got your database messed up.

And again, I’m going to strongly suggest that you stop posting images. They’re not readable by everyone on every device, and they can’t be quoted or copied to identify specific issues.

Please read How to use user as foreign key - #6 by KenWhitesell

As checked, the database did corrupt as you said.

Considering that my app is still in the developing stage, I have dropped the db and recreated the schema to get the issue fixed.

Thanks for your insight :slight_smile:

Regards,
Kelvin

i cant do that becuase there are more than 1 user in users can i just give this field the authenticated user instead

I’m sorry, you’re jumping into a solved topic from more than 9 months ago. If you have a question or issue, please open a new topic for discussion with the details of the issue you’re trying to resolve.