Django 右加入多对一关系

Django right-join on many-to-one relationship

在我的系统中,我有 Account 模型,其中有许多 Location 如下:

class Account(models.Model):
    # ... also contains billing address data

class Location(models.Model):
    account = models.ForeignKey('Account')
    # ... also contains physical address data

我想创建一个搜索视图,允许用户根据账单地址或实际地址搜索 Account 对象,并在 table 中显示结果,其中包含一个 [=11] =] 每个关联的 Location 对象的条目。我不能用 Account 模型的左连接来做到这一点;这会导致每个 Account 对象都有一个条目,因此不会涵盖与 Account 关联的所有 Location 对象(我不关心不关联的位置与帐户)。

相反,我想通过从 Location 模型到 Account 模型的右连接来执行此操作。这样一来,所有帐户都至少包含一次,并且每个帐户关联的每个位置都包含一次,并且与帐户关联的每个位置也包含在内。

有没有办法在 Django 1.8+ 中做到这一点?

编辑:Account 个对象不需要关联 Location 个对象,并且将来 Location.account is NULL == True 某些 Location 个对象可能是这种情况。

事实证明,利用 Django 对 many-to-many 关系的 through 声明可以更轻松地实现我的目标。我明确定义 link table:

class AccountLocation(models.Model):
    account = models.ForeignKey(Account)
    location = models.ForeignKey(Location, null=True, blank=True)

...然后我在Account模型上声明AccountLocation之间的关系:

locations = models.ManyToManyField(Location, through='AccountLocation')

最后,我实现了自定义 save()delete() logic on theAccountandLocationmodels. TheAccountmodel automatically puts a one-sided entry intoAccountLocationwhenever a newAccountinstance is created, and theLocationmodel removes one-sided entries in the link table when aLocationinstance is created or creates one when the lastLocationlinked to anAccount` 已删除。

此解决方案满足我的所有要求,因为我可以使用 AccountLocation 作为我的搜索 table,每个帐户在 table 中始终至少有一个条目,并且可以同时搜索 运行 来自 Account 模型和 Location 模型的数据。

Django 不支持 right-joins,但可以通过其他方式实现相同的结果。