首页 > 解决方案 > 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
    )

标签: pythondjango

解决方案


您可以列出与匹配寄存器相关的所有匹配项,然后将其从匹配项中完全排除,如下所示:

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)

推荐阅读