Django Complex查询以获取数据

时间:2014-03-08 06:42:37

标签: django django-models django-queryset

我有一些相关的模型:

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

class Organisation(CommonInfo):
   ORGANISATION_TYPE = (('C', 'Company'),
                     ('P', 'Product provider'),
                     ('D', 'Demo Company'))
   type_of_organisation = models.CharField(choices=ORGANISATION_TYPE, max_length=1) 
   name = models.CharField(max_length=50)
   organisation_details = models.OneToOneField('OrganisationDetails', null=True, blank=True, related_name='organisation')

class OrganisationUser(CommonInfo):
  TYPE_OF_USER = (('D', 'Demo user'),
                ('R', 'Registered user'))
  type_of_user = models.CharField(choices=TYPE_OF_USER, default='D', max_length=1)
  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)

我需要查询以获取属于特定公司的经理奖励的所有标签。

我想在views.py中执行类似的操作:

   def get_gems_for_manager_and_peers(self, request, *args, **kwargs):
         org_user = request.user.organisation_user 
         tags = Reward.objects.values('tag').filter(manager__exact=org_user.id,----query to check -manger_belong to particular_organisation---

所以,问题是找到特定组织的所有经理。或者还有其他方法可以做到这一点。

1 个答案:

答案 0 :(得分:1)

我需要查询以获取属于特定公司的经理奖励的所有标签

也许我误解了你,但这应该是非常简单的:

org_user = request.user.organisation_user
Tag.objects.filter(rewards__manager=org_user).distinct()