模型没有外部对象或外部字段的 Django 过滤器等于

Django filter where model doesn't have a foreign object or foreign field is equal to

我有两个模型 CommunityUserCommunity

社区模式

class Community(models.Model):

    # Community name
    name = models.CharField(max_length=64)
    slug = models.CharField(max_length=40, blank=True)
    admins = models.ManyToManyField(
        settings.AUTH_USER_MODEL, related_name="admins", blank=True
    )
    admins = models.ManyToManyField(
        settings.AUTH_USER_MODEL, related_name="admins", blank=True
    )
    members = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name="members",
        blank=True,
    )
    ------

用户社区模型

class UserCommunity(models.Model):

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=CASCADE, related_name="user"
    )
    group = models.ForeignKey(
        Community, on_delete=CASCADE, related_name="group")
    role = models.CharField(max_length=15, blank=True, null=True)
    # True is in community, false is not in community
    active = models.BooleanField(null=True, blank=True)

我需要获取用户不属于社区的所有社区对象,并且社区至少应有 1 名成员

我试过使用这个

Community.objects.filter(group__user=request.user.id, group__active=False,state=location.state, group_discoverability="public").exclude(
        hofAdmins__isnull=True, admins__isnull=True, members__isnull=True)[:10]

但是这个returns社区里面有一个UserCommunity对象,UserCommunity对象是在用户加入社区的时候创建的。 任何帮助将不胜感激,谢谢!

您可以使用:

Community.objects.<strong>exclude(</strong>
    group__user=request.user,
    group__active=True
<strong>)</strong>.exclude(
    mebers=request.user
).exclude(
    admins=request.user
)

因此,从 UserCommunityactive=Trueuser=request.user.

的那一刻起,这将排除 Community

或者当社区应该至少有一名成员时:

Community.objects.filter(
    <b>group__active=True</b>
).<strong>exclude(</strong>
    group__user=request.user,
    group__active=True
<strong>)</strong>.exclude(
    mebers=request.user
).exclude(
    admins=request.user
)<b>.distinct()</b>

我还建议删除许多 ManyToManyField:您的 UserCommunity 已经是用户模型和 Community 之间的 junction table [wiki]。例如,您可以添加一个字段 role 来消除成员和管理员之间的歧义。通过制作多个many-to-many表,查询效率会降低,注解会比较麻烦。


Note: The related_name=… parameter [Django-doc] is the name of the relation in reverse, so from the User model to the Community model in this case. Therefore it (often) makes not much sense to name it the same as the forward relation. You thus might want to consider renaming the admins relation to admin_communities.

Community.objects.filter(~Q(members__in=[request.user.id]), ~Q(hofAdmins__in=[request.user.id]), ~Q(admins__in=[request.user.id]), state=location.state, group_discoverability="public").exclude(         hofAdmins__isnull=True, admins__isnull=True, members__isnull=True)[:10]