DEV Community

AkshayKumarC132
AkshayKumarC132

Posted on

How to create a relations between primary key and foreign key in Django models and POST values into DB

I have a Django app which is basically an Online shopping. Right now I have two models: User_details and Extend_user_deatils.

In User_details I have(Username, Firstname, lastname, email, etc..). Now after that i need to extend User_details Model with Other Fields so I have Created another Model Extend_user_deatils consisting of (Mobile , Age) columns.

Now i need to Link those Two Models, for that I have written an `logic with Foreign Key Reference

`
class User_details(models.Model): #Table 1
id = models.AutoField(primary_key=True, db_column='user_id')
username = models.CharField(max_length=50)
first_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
email = models.CharField(max_length=50)

class Extend_user_details(models.Model): #Table 2
user =models.ForeignKey(User_details, on_delete=models.CASCADE,db_column='user_id')
mobile = models.BigIntegerField(blank=True, null=True)
age = models.IntegerField(blank=True, null=True)
`

When I Open Django admin Page and Post the Data it is Working Fine and Values are posting into DB.

When I register as a User from register page . ForeignKey Column(user) from Table2 is showing Null .apart from that all the inputs is posting into DB as shown
Image description

Is there any way to solve this issue

Thanks in Advance

Top comments (0)