Reputation: 147
I am creating an app in which it manages ranking and ELO functions for a local hobby game store. I am using django to write the application. I am having troubles trying to figure out how to access a user's model from their name.
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
mtg_currentELO = models.IntegerField(default=1000)
mtg_highestELO = models.IntegerField(default=1000)
mtg_lowestELO = models.IntegerField(default=1000)
def __str__(self):
return self.user.username
views.py
def home(request):
users = User.objects.all()
if request.method == 'GET':
user1 = User.objects.get(username=request.POST['player1'])
user2 = User.objects.get(username=request.POST['player2'])
print(user1, user2) # DEBUG LINE -- it does find
print(user1.mtg_currentELO) # DEBUG LINE -- it does NOT FIND
So what I'm trying to accomplish is the find mtg_currentELO
from the user1. However, I can't access it via user1.mtg_currentELO
. How can I access the property mtg_currentELO
of a Profile
, via the user's name?
Upvotes: 0
Views: 690
Reputation: 684
You should assign a related name to OneToOneField like this:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="assigned_profile")
...
then you will be able to access it like user1.assigned_profile.mtg_currentELO
You can find details here: https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.OneToOneField
Upvotes: 1