user1575045
user1575045

Reputation: 55

Django query to filter username in correct format

There is model OraganisationUser :

class OrganisationUser(CommonInfo): 
    active = models.BooleanField(default=True)
    user = models.OneToOneField(User, related_name='organisation_user')
    managers = models.ManyToManyField('self', related_name='employees_managed', null=True, default=None, blank=True, symmetrical=False)
    approvers = models.ManyToManyField('self', related_name='approvees', null=True, default=None, blank=True, symmetrical=False)
    organisation = models.ForeignKey(Organisation, related_name='employees')
    user_details = models.OneToOneField('OrganisationUserDetails', null=True, blank=True)
    super_admin = models.ForeignKey('self', related_name='organisation_employees', null=True, blank=True)
    objects = OrganisationUserManager()
    gems = models.PositiveIntegerField(default=0, null=True, blank=True)
    rank = models.PositiveIntegerField(default=0, null=True, blank=True)

I have written a query to filter user name in views.py :

username = OrganisationUser.objects.filter(user = id)
print username

Its printing :  [<OrganisationUser: nirmal>]

I want to fetch nirmal from above result.

Upvotes: 1

Views: 3661

Answers (2)

AlvaroAV
AlvaroAV

Reputation: 10563

The problem in your code is that 'username' has the organisationuser object. With that object (in your code username), you can access any atribute like active,user,managers,organisation,userdetails.... just adding a dot between object and atribute.

You can do it like this:

orguser = OrganisationUser.objects.filter(user = id)
print orguser  #This print the object OrganisationUser
print orguser.user  #This print the object User, wich the onetoonefield is pointing to
print orguser.user.username #This print the username, of the user pointed by the one to one field

Example managing django object. Get attribute value:

object =  OrganisationUser.objects.filter(user = 1)  #Get the object with id=1
print object.active  #This will print the value for this attribute (active)

Upvotes: 0

Pavel Anossov
Pavel Anossov

Reputation: 62948

filter returns a list of objects. Use get to get a single object and navigate to the username:

username = OrganisationUser.objects.get(user=id).user.username

Better yet, look up the user directly

username = User.objects.get(pk=id).username

 

Is there a possibility of not finding the user with that id?

 

Where are you getting the id? Is this the logged in user? Then he is available in request.user, and his username in request.user.username.

Upvotes: 1

Related Questions