Django查询以正确的格式过滤用户名

时间:2014-03-05 11:27:53

标签: django django-models django-queryset

有模型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)

我编写了一个查询来过滤views.py中的用户名:

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

Its printing :  [<OrganisationUser: nirmal>]

我想从上面的结果中获取 nirmal

2 个答案:

答案 0 :(得分: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中有用户名。

答案 1 :(得分: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)