我有两个模型如下:
class UserSelection(models.Model):
soccerseason = models.IntegerField()
fixturematchday = models.IntegerField()
userid = models.IntegerField()
campaignno = models.IntegerField()
teamselection = models.IntegerField()
teamselectionid = models.IntegerField()
teamresult = models.CharField(max_length = 1)
teamgoals = models.IntegerField()
class StraightredTeam(models.Model):
teamid = models.IntegerField(primary_key=True)
teamname = models.CharField(max_length=36)
teamcode = models.CharField(max_length=5)
teamshortname = models.CharField(max_length=24)
currentteam = models.PositiveSmallIntegerField()
def natural_key(self):
return self.teamshortname
class Meta:
managed = True
db_table = 'straightred_team'
在我看来,我创建了包含两个查询结果的变量,如下所示:
currentTeams = StraightredTeam.objects.filter(currentteam=1).order_by('teamshortname')
cantSelectTeams = UserSelection.objects.filter(campaignno=398169).order_by('fixturematchday')
基本上,我想从cantSelectTeams中的当前团队选择中排除团队。链接这两者的字段是来自StraighRedTeam的teamid和来自UserSelection的teamselectionid。
我知道我可以单独运行这两个查询并通过在python中操作它来创建一个列表,但我只是想知道我是否可以使用查询来完成它,也许可以将两者结合起来?
如果您需要更多信息,请询问。如果您不喜欢这个问题并进行投票,那么请提供反馈,为什么我可以在将来提出更好的问题。
非常感谢,艾伦。
答案 0 :(得分:3)
首先,你做错了。真的错了。您最好使用ForeignKeys将模型链接在一起。
回答这个问题,是的,你可以做到,而且非常简单:
cantSelectTeams = UserSelection.objects.filter(campaignno=398169).order_by('fixturematchday')
currentTeams = StraightredTeam.objects.filter(currentteam=1).exclude(teamid__in=cantSelectTeams.values_list('teamselectionid', flat=True)).order_by('teamshortname')