Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
多对一关系上的Django右连接_Django_Django Queryset_Right Join - Fatal编程技术网

多对一关系上的Django右连接

多对一关系上的Django右连接,django,django-queryset,right-join,Django,Django Queryset,Right Join,在我的系统中,我有和账户模型,其中有许多位置s,如下所示: class Account(models.Model): # ... also contains billing address data class Location(models.Model): account = models.ForeignKey('Account') # ... also contains physical address data 我想创建一个搜索视图,允许用户根据账单地址或物理地

在我的系统中,我有和
账户
模型,其中有许多
位置
s,如下所示:

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

class Location(models.Model):
    account = models.ForeignKey('Account')
    # ... also contains physical address data
我想创建一个搜索视图,允许用户根据账单地址或物理地址搜索
帐户
对象,并将结果显示在一个表中,每个关联的
位置
对象都有一个
帐户
条目。我不能从
帐户
模型中使用左连接;这导致每个
帐户
对象都有一个条目,因此不包括与
帐户
关联的所有
位置
对象(我不关心与帐户无关的位置)

相反,我想通过从
位置
模型到
帐户
模型的右连接来实现这一点。这样,所有帐户都至少包含一次,并且每个与帐户关联的位置都包含一次,与帐户关联的每个位置也包含一次

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


编辑:
Account
对象不需要关联
位置
对象,将来可能会出现这样的情况,对于一些
Location
对象,
Location.account为NULL==True

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

class AccountLocation(models.Model):
    account = models.ForeignKey(Account)
    location = models.ForeignKey(Location, null=True, blank=True)
…然后我在
帐户
模型上声明
帐户
位置
之间的关系:

locations = models.ManyToManyField(Location, through='AccountLocation')
最后,我在
Account
Location
模型上实现了自定义的
save()
delete()逻辑。每当创建新的
Account
实例时,
Account
模型会自动将单面条目放入
AccountLocation
,而
Location
模型在创建
Location
实例时删除链接表中的单面条目,或者在删除链接到
帐户的最后一个
Location
实例时创建单面条目

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

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