简体   繁体   中英

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_details .

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 a logic with Foreign Key Reference as:

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 Screenshot

Is there any way to solve this issue?

sometimes when you are creating foreignKey, Django will make a separate table in DB to store the foreignkey values especially when you use the shell to do queries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM