【问题标题】:Django right-join on many-to-one relationshipDjango 右连接多对一关系
【发布时间】:2016-03-19 13:02:04
【问题描述】:

在我的系统中,我有和Account 有很多Locations 的模型如下:

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

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

我想创建一个搜索视图,允许用户根据帐单地址或实际地址搜索 Account 对象,并将结果显示在一个表中,每个关联的 Location 对象都有一个 Account 条目.我不能用Account 模型的左连接来做到这一点;这会为每个 Account 对象生成一个条目,因此不会涵盖与 Account 关联的所有 Location 对象(我不关心与帐户无关的位置)。

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

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

编辑:Account 对象不需要关联Location 对象,将来可能会出现Location.account is NULL == True 与某些Location 对象相关的情况。

【问题讨论】:

    标签: django django-queryset right-join


    【解决方案1】:

    事实证明,利用 Django 的多对多关系的through 声明可以更轻松地实现我的目标。我明确定义了链接表:

    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 newAccountwhenever a newAccountinstance is created, and theLocationmodel removes one-sided entries in the link table when aLocationlinked to anLocation@Account`987654336@Account已删除。

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

    Django 不支持右连接,但可以通过其他方式实现相同的结果。

    【讨论】:

      猜你喜欢
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 2010-11-25
      相关资源
      最近更新 更多