我有两个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
)
答案 0 :(得分:0)
您可以将__isnull
过滤器与正确的related_query_name
(默认为小写型号名称)一起使用:
Match.objects.filter(matchregister__isnull=True)
答案 1 :(得分:0)
您可以列出与匹配寄存器关联的所有匹配项的列表,然后将其从匹配项中完全排除,如下所示:
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)