Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.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
Python 使用django排除空m2m字段的筛选器问题_Python_Django_Orm - Fatal编程技术网

Python 使用django排除空m2m字段的筛选器问题

Python 使用django排除空m2m字段的筛选器问题,python,django,orm,Python,Django,Orm,我构建的queryset错误地遗漏了一些项。我在Django有三种型号: class Case(models.Model): agents = models.ManyToManyField('UserProfile', related_name='agent_of', blank=True, null=True) organization = models.ForeignKey(Organization, related_name='case_org') class User

我构建的queryset错误地遗漏了一些项。我在Django有三种型号:

class Case(models.Model):
    agents = models.ManyToManyField('UserProfile', related_name='agent_of', blank=True, null=True)
    organization = models.ForeignKey(Organization, related_name='case_org')


class UserProfile(models.Model):
    name = models.CharField(max_length=40)
    user = models.ForeignKey(User, unique=True, related_name='user_profile')
    organization = models.ForeignKey(Organization, related_name='org_members', blank=True, null=True)

class Organization(models.Model):
    name = models.CharField(max_length=75)
我正试图建立一个未分配案例的列表。也就是说,当前用户不是其上的代理的情况,包括根本没有为其分配代理的情况。我的问题是:

Case.objects.filter(
             organization=request.user.user_profile.get().organization.id).exclude
             (Q(agents__user=request.user))
这适用于分配了其他代理(UserProfile模型)的情况。但它不会返回没有指定代理的案例。我很确定这与没有分配代理的案例在中间表中没有连接UserProfiles和cases的行这一事实有关

换句话说,如果我有这些案例:

案件/代理人

案例1:汤姆,史蒂夫

案例2:史蒂夫

案例3:简

案例4:没有人

我的查询将返回Case2和Case3,但不会返回Case4。试图把那个案子包括在内


抱歉,如果这不是很清楚,请提供帮助。

问题有点不清楚,但此查询是否无法获取所有未分配给该用户的案例

Case.objects.exclude(agents=request.user)
如果您试图获取属于用户组织且未分配给用户的案例或未未分配给任何人的案例,则此操作应有效

Case.objects.filter(Q(organization=organization)|Q(agents=None)).exclude(agents=request.user)

谢谢由于我的业务规则(也是我的错,因为我不是很清楚),这个查询并不完全正确,但它让我走上了正确的轨道。我不知道为什么我在排除中使用了Q()对象,因为我没有做任何类型的高级排除,或者&or |。因此,与您的查询一样,我只是将exclude agents=request.user设置为,这样就解决了问题。我想Q的表现可能会有点不同。以下是对我有效的查询:
Case.objects.filter(组织=请求.user.user\u profile.get().organization.id)。filter(状态=Case.OPEN\u状态)。exclude(代理\用户=请求.user)