简体   繁体   中英

Query in django models

Reward 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')

and certificate 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.

I have query to take out rewardee names from rewards models :

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

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

I want to fetch nirmal_4 and nirmal_1 using this query . These are rewardee names.

How to do this?

Its printing [<Reward: reciever-nirmal_4, tag-123>, <Reward: reciever-nirmal_1, tag-SDF34>] because those are Reward objects. And in fact, it is fetching exactly those two objects which you want.

Now, if you want to print rewardee names, then you can loop over the objects and print rewardee names as:

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

Here, approver is still an object of OrganisationUser. So, if this object has a name then you can do print each.approver.name

Another option is, in your models.py, define a unicode function to the model as:

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

This function is used to set the name of object for recognizing it. So, you can set the name of reward object with its approver name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM