Home > front end >  how to store user data from user model inside a database table in django
how to store user data from user model inside a database table in django

Time:03-29

I have a Buyer table in mysql database and I want to take the username , email, password from User model ( default django model ) and store it inside Buyer table, Buyer model in models.py:

class Buyer(models.Model):
row_id = models.AutoField(primary_key=True)
user_name = models.CharField(unique=True, max_length=50)
user_password = models.CharField(max_length=16)
first_name = models.CharField(max_length=50)
middle_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50)
email = models.CharField(unique=True, max_length=100)
home_phone = models.CharField(max_length=20, blank=True, null=True)
mobile_phone = models.CharField(unique=True, max_length=20)
personal_id = models.CharField(max_length=30, blank=True, null=True)
idtype_fk = models.ForeignKey('Idtype', models.DO_NOTHING, db_column='idType_FK', blank=True, null=True)  # Field name made lowercase.
personal_id_country_fk = models.ForeignKey('Country', models.DO_NOTHING, db_column='personal_id_country_FK',related_name='personal_id_country_fk')  # Field name made lowercase.
address_line_1 = models.CharField(db_column='address_Line_1', max_length=200)  # Field name made lowercase.
address_line_2 = models.CharField(db_column='address_Line_2', max_length=200, blank=True, null=True)  # Field name made lowercase.
p_o_box = models.CharField(max_length=20, blank=True, null=True)
city = models.CharField(max_length=50)
country_fk = models.ForeignKey('Country', models.DO_NOTHING, db_column='country_FK' , related_name='country_fk')  # Field name made lowercase.
gender_fk = models.ForeignKey('Gender', models.DO_NOTHING, db_column='gender_FK')  # Field name made lowercase.
bdate = models.DateField()

def __str__(self):
    return 'User: '   self.user_name

class Meta:
    managed = False
    db_table = 'buyer'

and after the registration User/Buyer can add more information such as first name , mobile phone etc.. in the profile page

CodePudding user response:

As Willem van Onsem mentioned, use a ForeignKey in your Buyer model to reference to the user object:

class Buyer(models.Model):
    #other stuff
    user_fk = models.ForeignKey(User, on_delete=models.SET_NULL)
    #other stuff

Or, if every Buyer is just one User and every User is just one Buyer, use a OneToOneField instead of a ForeignKey.

If you would then want to access the username/email/password you can use a query like this:

buyer = Buyer.objects.all().first()    
buyer_email = buyer.user_fk.email
  • Related