Search code examples
djangodjango-modelsmysql-pythontable-relationshipsdb-schema

Best way to mange user information into two tables using OneToOne Realtion in django


Please guide and suggest me the best way to solve this problem.

I have a user information table:

first: username, first_name, last_name, email, password [ provided by django ]

Second: mobile, parent_id and other user profile related details [ want to create ]


Goal: I want the second table with some fields and connect with the auth_user ( the name provided by django ) through OneToOne relation so I can fectch all the field through one object.


What I have tried

1 case
I created a second table and connect with FK relation and download all previous data from the previous DB and sperate data manually and uploaded through CSV into new tables.

Problem: I cannot access both table data through a single object.

2nd case So I update the second table with OneToOne relation.

Problem: add new users with this relation is perfectly fine but when trying to edit/ change previously saved data then got error

error: invalid literal for int() with base 10 during change in models

Note: Hundreds of user in the previous table, just safly migrate with new DB schema.

Please, give me a tricky idea to fix this issue.

Thanks to all.

Kudos to the savior.


code:

views.py [file]

...
@login_required()
def register(request, epin):
    EPin = apps.get_model('epin', 'EPin')
    if EPin.objects.filter(epin__exact=epin, is_active=1,
                           assigned_to=request.user.username).exists():
        form = RegistrationForm()
        if request.method == 'POST':
            form = RegistrationForm(request.POST)
            if form.is_valid():
                if User.objects.filter(username__exact=request.POST['parent_id']).exists():
                    try:
                        with transaction.atomic():
                            username = generate_username()
                            password = generate_password()
                            EPin.objects.filter(epin__exact=epin,
                                                is_active=1).update(used_by=username, is_active=0,
                                                                    used_at=datetime.now())
                            Profile(mobile=request.POST['mobile'],
                                    leg=request.POST['leg'],
                                    product_id=request.POST['product'],
                                    parent_id=request.POST['parent_id'],
                                    user_id=username).save()

                            User.objects.create_user(username=username, password=password,
                                                     email=request.POST['email'],
                                                     first_name=request.POST['first_name'],
                                                     last_name=request.POST['last_name'])

                            logging.getLogger('info_logger').info('U : '+username+' P : '+password)
                    except Exception as e:
                        messages.warning(request, e)
                        logging.getLogger('error_logger').error(e)
                    # try:
                    #     user_msg = 'Username :' + username + ' and Password : ' + password
                    #     send_mail('Successfully registered ', user_msg,
                    #               '[email protected]', [request.POST['email']])
                    # except Exception as e:
                    #     messages.warning(request, e)
                    #     logging.getLogger('error_logger').error(e)
                    # try:
                    #     user_msg = 'Username :' + username + ' and Password : ' + password
                    #     send_message(user_msg, request.POST['mobile'])
                    # except Exception as e:
                    #     messages.warning(request, e)
                    #     logging.getLogger('error_logger').error(e)

                    messages.success(request,
                                     'New User successfully created!, Username and password sent on mobile and email.')
                    return redirect('epin')
                else:
                    messages.warning(request, 'Invalid Sponsor ID, User not exists')
        return render(request, 'users/register.html', {'form': form})
    else:
        messages.warning(request, 'Not a valid E-Pin -- ' + epin)
        logging.getLogger('error_logger').error(epin+' not valid')
        return redirect('epin')



models.py [file]

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # user_id = models.CharField(max_length=10)
    mobile = models.CharField(max_length=20)
    parent_id = models.CharField(max_length=10)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


    def __str__(self):
        return f'{self.user.username}'

Solution

  • To relate Django´s user model as a Foreign key in another model use the following:

    from django.contrib.auth.models import User
    from django.contrib.auth import get_user_model
    
    user = models.ForeignKey(get_user_model(), help_text="User", blank=True, null=True, on_delete=models.CASCADE)