在Django中检查多对多成员

时间:2018-11-12 19:10:26

标签: python django django-orm

我有以下用户类别,

class User(AbstractBaseUser, PermissionsMixin, Base):
    email = models.EmailField(db_index=True, unique=True, max_length=255)
    mobile = PhoneNumberField(null=True)
    username = models.CharField(db_index=True, null=False, unique=True, max_length=255)

我有以下房间对象,

class Room(Base):
    name = models.CharField(db_index=True, unique=True, max_length=255)
    status = models.CharField(default=RoomStatus.ACTIVE, max_length=255, null=True)
    members = models.ManyToManyField(User)
    last_activity = models.DateTimeField(default=timezone.now)

我正在尝试查找用户是否作为成员存在于会议室中

user = User.objects.get(id=kwargs.get('user_id'))
room = Room.objects.get(id=kwargs.get('room_id'))

这不起作用,

member = room.members.filter(user=user)

如何正确执行此操作

1 个答案:

答案 0 :(得分:2)

通过单个查询,您可以过滤:

tempFile.write( str(customerInfo.name) + '\n')

或者如果仍然需要Room.objects.filter(id=kwargs['room_id'], members__id=kwargs['user_id']).exists() Room

User

您还可以为room = Room.objects.get(id=kwargs['room_id']) user = User.objects.get(id=kwargs.get('user_id')) if user in room.members.all(): # ... pass 过滤room.members

id=user_id