2014-03-05 52 views
0

過濾器的用戶名有模型OraganisationUser:Django的查詢,以正確的格式

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) 

我寫了一個查詢在views.py過濾用戶名:

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

Its printing : [<OrganisationUser: nirmal>] 

我想獲取尼爾默爾從上面的結果。

回答

0

filter返回對象列表。使用get得到一個對象並導航到用戶名:

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

更重要的是,查找用戶直接

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

 

有沒有找到與用戶的可能性那個ID?

 

你在哪裏得到id?這是登錄用戶嗎?然後他可以在request.user和他的用戶名request.user.username

0

你的代碼中的問題是'username'有organisationuser對象。使用該對象(在您的代碼用戶名中),您可以訪問任何屬性,如活動用戶,管理員,組織,用戶代碼......只需在對象和屬性之間添加點即可。

你可以這樣說:

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 

實例管理Django的對象。獲取屬性值:

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