Home > Enterprise >  Find user name and last name Query Django
Find user name and last name Query Django

Time:11-20

In my Django app I have module 'users' which I use to create profiles. I need help on how to query and find user name and last name depending on Profile in 'users'.

users/models.py

from django.db import models
from django.contrib.auth.models import User
from PIL import Image
from blog.models import Odjel

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    department = models.ForeignKey(Odjel, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Odjel")
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')


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

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

I'm not sure, but how can I find 'user.first_name' and 'user.last_name' using only Profile. Something like:

queryset = User.objects.values('first_name').filter(Profile=Profile_var)

views.py

from users.models import Profile
from django.http import JsonResponse, HttpResponseRedirect
from .models import Post, User, File
from users.models import Profile

def load_persons(request):
    #this is Ajax call from my HTML page/script
    department = request.GET.get('department')


    print(profile = Profile.objects.filter(department_id=department))

as result I get <QuerySet [<Profile: JJon Profile>]> I need to Query with JJon to get: Name: John and Last name: Jon

Tried so far:

    username = User.first_name.filter(profile=profile)
AttributeError: 'ForwardOneToOneDescriptor' object has no attribute 'first_name'

 username = Profile.first_name.filter(profile=profile)
AttributeError: type object 'Profile' has no attribute 'first_name'

    username = Profile.user.first_name.filter(profile=profile)
AttributeError: 'ForwardOneToOneDescriptor' object has no attribute 'first_name'

CodePudding user response:

try this

Profile.objects.filter(pk=profile_id).values('user__first_name','user__last_name')

UPDATE for specific purpose.

def load_persons(request):
    #this is Ajax call from my HTML page/script
    department = request.GET.get('department')
    profile = Profile.objects.filter(department_id=department)
    if profile:# we check that the profile exists first
        first_name = profile[0].user.first_name 
        last_name = profile[0].user.last_name 

CodePudding user response:

Let's suppose that you have a profile instance of Profile object. As the User object is an OneToOneField to the Profile object. Then if you have a profile instance:

username = profile.user.user_name
last_name = profile.user.last_name

More about Django OneToOneField

  • Related