0

我有两个模型:

class PlayerPermissionGroup(models.Model):
  player = models.ForeignKey(Player)
  name = models.CharField(max_length=200)

class PlayerPermissionGroupMember(models.Model):
  permission_group = models.ForeignKey(PlayerPermissionGroup)
  user = models.ForeignKey(User)

目前,要获得权限组中的所有成员,我会这样做:

getMembers(group):
  group_member_ids = (PlayerPermissionGroupMember.objects.filter(permission_group=group)
                                                         .values_list('user__id'))
  return User.objects.filter(pk__in=group_member_ids)

有没有更好/更清洁的方法来做到这一点?

4

1 回答 1

1

您可以related_name向您的 FK添加一个User

class PlayerPermissionGroupMember(models.Model):
  permission_group = models.ForeignKey(PlayerPermissionGroup)
  user = models.ForeignKey(User, related_name='player_permision_groups')

然后你可以这样做:

getMembers(group):
  return User.objects.filter(player_permision_groups__permission_group=group)

您可以省略 ,但使用django 分配related_name的默认值会稍微改变查找。related_name

于 2013-05-08T01:36:22.807 回答