Search code examples
pythondjangodjango-modelsdjango-users

Python - Django query using auth.User model as OneToOneField


I am using the auth.User model for login info, and a custom UserProfile model for all of a user's profile data.

The auth.User.username is a random string. and the UserProfile.user is the same string.

When attempting to query the database table "UserProfile" I get the following error:

ValueError: invalid literal for int() with base 10: '3df69698-c97d-11e7-a924-b0c0905e8512'

models.py

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=256, default=None)
    last_name = models.CharField(max_length=256, default=None)
    ...

    def __str__(self):
        return str(self.user)

views.py

from .models import UserProfile
from django.contrib.auth.models import User

def get_users(request):
    data = json.loads(request.body.decode('utf-8'))
    user_id = escape(data['id'])

    # error occurs here
    user_pref = UserProfile.objects.get(user=user_id)

The problem comes when trying to query the database, and using a string compared to an auth.User object. I do not know how to get around this?


Solution

  • Is that string supposed to be the username? If so you should query that field explicitly:

    UserProfile.objects.get(user__username=user_id)