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

Neon image

Serverless Postgres in 300ms (❗️)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free →

Top comments (0)

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple “thank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay