python - Django查询获取不在其他对象中的对象
问题描述
我有两个 Django 模型:Match 和 MatchRegister。我想获取不在 MatchRegister 对象中的所有匹配项的列表,但我无法这样做。你能帮我实现它吗?
在我的两节课下面
class Match(models.Model):
"""Model representing Match object"""
match_number = models.CharField(
max_length=10
)
home_team = models.ForeignKey(
Team,
on_delete=models.SET_NULL,
null=True,
related_name='home_team'
)
away_team = models.ForeignKey(
Team,
on_delete=models.SET_NULL,
null=True,
related_name='away_team'
)
match_category = models.ForeignKey(
MatchCategory,
on_delete=models.SET_NULL,
null=True
)
date_time = models.DateTimeField(
default=timezone.now
)
notes = models.TextField(
max_length=1000,
blank=True
)
last_update = models.DateTimeField(
auto_now=timezone.now
)
class MatchRegister(models.Model):
match = models.ForeignKey(
Match,
on_delete=models.SET_NULL,
null=True
)
解决方案
您可以列出与匹配寄存器相关的所有匹配项,然后将其从匹配项中完全排除,如下所示:
all_match_registers = MatchRegister.objects.all()
ids_to_exclude = []
for match_register in all_match_registers:
ids_to_exclude.append(match_register.match.id)
Match.objects.exclude(id__in = ids_to_exclude)
推荐阅读
- javascript - 从 API 对象呈现对象属性的问题
- google-apps-script - 无法为整个域安装编辑器插件
- java - 从游戏板上获取最后一步
- pari - PARI/GP 中的位数
- reactjs - 在带有 react-router 的 React 中,如何在离开复杂视图时保留一个人的所有视图选择,然后直接返回?
- git - 从本地分支推送到上游分支
- javascript - 使用 i18n 的参数中的日期
- html - 如何从居中的导航栏徽标中删除边距以给链接更多空间
- sqlite - 访问 Akavache DatabasePath 值
- node.js - 为什么不是所有值都存储在 mongodb 中?