将自定义关系数据添加到Django查询结果

时间:2015-10-05 20:20:52

标签: sql django django-queryset

我有两个模型,包含一对多,通过外键和多对多关系。如何将我的关系中的额外数据添加到我的组合查询集中。外键关系将具有硬编码的额外关系数据,而多对多关系将从关联表中获取额外数据。

模型的相关细节如下所示:

class Player(BaseModel):
    user = models.ForeignKey('User', related_name='players', null=True)
    player_name = models.CharField(max_length=500)

class User(AbstractUser, BaseModel):
    full_name = models.CharField(max_length=64, default='')
    watched_players = models.ManyToManyField('Player', through='Role', related_name='watchers')

class Role(models.Model):
    """
    User <-> Player relation
    """
    ROLE = (
        ('Instructor', 'Instructor'), # user is instructor of the player, has read, update access
        ('Spectator', 'Spectator'),   # user is spectator of the player, has read access to data
    )

    user = models.ForeignKey('User', related_name='roles')
    player = models.ForeignKey('Player', related_name='roles')
    role = models.CharField(max_length=10, choices=ROLE, default='Spectator')

我想返回与给定用户关联的所有玩家的列表以及相关角色。请注意,外键的角色应作为&#34; Owner&#34;返回。在原始SQL中,我会执行以下操作(假设我的用户的ID为2):

select p.player_name, role from player p join role r on p.id=r.player_id where r.user_id=2
union
select p.player_name, 'Owner' from player p where p.user_id=2;

我可以通过以下方式获得我想要的所有球员:

Player.objects.filter(user=user) | Player.objects.filter(watchers=user)

但这并没有让我获得额外的“#34”角色。值。

0 个答案:

没有答案