如何获取在 ManyToManyField 中有对象的对象?

How to get objects which have an object in their ManyToManyField?

有这个型号:

class User(AbstractUser):
    followers = models.ManyToManyField('self', symmetrical=False, related_name='followings', null=True, blank=True)

假设我有一个名为 'A' 的用户对象。在一个视图中,我想过滤具有 'A' 作为其关注者的用户对象。我该怎么做?

您可以查询:

A<strong>.followings.all()</strong>

related_name=… [Django-doc] 是反向关系的名称,因此它是 UserQuerySet 具有 A 作为 follower

如果您不指定 related_name=…,它将采用小写形式的模型名称,后跟 …_set 后缀,因此在这种情况下为 user_set

如果你只有A的主键,那么你可以查询:

User.objects.filter(<b>followers__id=a_id</b>)

Note: Using null=True [Django-doc] for a ManyToManyField [Django-doc] makes no sense: one can not enforce by the database that a ManyToManyField should be non-empty, therefore as the documentation says: "null has no effect since there is no way to require a relationship at the database level."