Reputation: 55
I used to use a OneToOneField relation to the User model, but I had to switch to foreign key (because I want to store multiple dates for 1 user). And now I can't seem to figure out how to refer to my data inside my view.
view.py
def get_data(request, *args,**kwargs):
data = {
'weight': request.user.user_profile.weight,
'goal': request.user.user_profile.goal,
'date': request.user.user_profile.created_at,
}
return JsonResponse(data)
models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from datetime import date
# Create your models here.
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_profile')
weight = models.FloatField(max_length=20, blank=True, null=True)
height = models.FloatField(max_length=20, blank=True, null=True)
goal = models.FloatField(max_length=20, blank=True, null=True)
created_at = models.DateField(auto_now_add=True)
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
Upvotes: 0
Views: 68
Reputation: 738
I think you should keep OneToOne field. If you want multiple dates you can create ForeignKey for the dates.
If you still want ForeignKey Profile-User, you can try to filter the Profile model, to get the particular profile you need, by username, date etc.:
profile = Profile.objects.get(user=request.user, created_at=request.user.date_joined)
data = {
'weight': profile.weight,
'goal': profile.goal,
'date': profile.created_at,
}
Upvotes: 1