查询django模型

时间:2014-03-06 06:04:39

标签: django django-models

奖励models.py

class Reward(CommonInfo):
     approved = models.BooleanField(default=False)
     manager = models.ForeignKey(OrganisationUser, related_name='rewards_given') #todo add contraint so that manager should be manager of this role
     approver = models.ForeignKey(OrganisationUser, null=True, related_name='approved_rewards', blank=True)# todo same as above but approver
     number_of_gems = models.PositiveIntegerField(null=True, db_column='number_of_gems', blank=True)
     tag = models.ForeignKey(Tag,related_name='rewards')
     role_history = models.ForeignKey(RoleHistory, related_name='rewards')
     certificate = models.OneToOneField(Certificate,related_name='reward')

和证书models.py:

class Certificate(models.Model):
   comments = models.TextField(blank=True, default='')
   generic_certificate = models.ForeignKey(GenericCertificate, related_name='certificates_awarded')
   tag = models.ForeignKey('Tag', related_name='certificates_awarded', null=True, blank=True)
   created_at = models.DateTimeField(auto_now_add=True)
   history_timestamp = models.DateTimeField(auto_now=True)
   #template = models.FileField(upload_to='certificate/rewarded_templates', null=True, blank=True)#this will be path of certificate generated for this particular employee
   rewardee = models.ForeignKey(OrganisationUser, related_name='certificates_rewarded')
#there will be location in server for certificates and it will be auto generated.

我有查询从奖励模型中取出获奖者名字:

 a= Reward.objects.filter(approved=True)
 print a 

Its printing  :  [<Reward: reciever-nirmal_4, tag-123>, <Reward: reciever-nirmal_1, tag-SDF34>]

我想使用此查询获取 nirmal_4 nirmal_1 。这些是获得者的名字。

怎么做?

1 个答案:

答案 0 :(得分:0)

打印[<Reward: reciever-nirmal_4, tag-123>, <Reward: reciever-nirmal_1, tag-SDF34>],因为它们是奖励对象。事实上,它正是取得你想要的那两个对象。

现在,如果你想打印获奖者名字,那么你可以循环对象并打印获奖者名称:

a= Reward.objects.filter(approved=True)
for each in a:
    print each.approver

此处,审批人仍然是OrganisationUser的对象。因此,如果此对象具有名称,则可以打印each.approver.name

另一个选择是,在models.py中,为模型定义 unicode 函数:

def __unicode__(self):
    return self.approver.name

此函数用于设置用于识别它的对象的名称。因此,您可以使用其批准者名称设置奖励对象的名称。