Hannan Hannan -4 years ago 156
Python Question

Django - how to query user profile based on User model having OneToOneField

I'm using Django and new to programming. I want to know how can I query the profiles of the user which has OneToOne relation with User model. Here is my code:

models.py:

class User(models.Model):

email = models.EmailField(unique=True, null=True)
date_joined = models.DateTimeField(default=datetime.now)
username = models.CharField(max_length=22)

class UserProfile(models.Model):

user = models.OneToOneField(User, on_delete=models.CASCADE)
company_name = models.CharField(max_length=500)
contact_person = models.CharField(max_length=255)
country = models.CharField(max_length=100)
city = models.CharField(max_length=100)


If a user signup and after verification fills in his profile. How can I query the database through views.py that for any particular User what is his UserProfile information. For example what is the company_name or country for a user with email example@examplemail.com

Just on the side note also is this the best practice I'm doing to capture additional information about user in Django?

Answer Source

You can get the User and use its UserProfile like so:

# Make sure you create a UserProfile when you create a new User
user = User.objects.get(email='example@examplemail.com')
user.userprofile.company_name
user.userprofile.country

Yes, this is a recommended way to add extra fields to the default django User model. See this question. If you are using your own User model you could just add the UserProfile fields to the User model.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download