Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

python - Django Foregin Key Count

I'm trying to get a count of the number of Users that are connected to a Room. A User can be connected to only one Room, a Room can have many Users.

My models look like this

class User(AbstractBaseUser, PermissionsMixin):
    """Database model for users"""
    screen_name = models.CharField(max_length=255, unique=True)
    room = models.ForeignKey(
        Room, related_name='room', on_delete=models.CASCADE
    )
    ...
class Room(models.Model):
    """Database model for rooms"""
    name = models.CharField(max_length=100)
    is_full = models.BooleanField(default=False)
    ...

What I'm trying to do is lock any instance of a Room out once a certain number of Users have been assigned to it. How do I go about finding the number of Users connected to a given room? Pseudo code of what I'm trying.

my_room.users.count >= max_users:
   my_room.is_full = True

Thank you in advance.

question from:https://stackoverflow.com/questions/65889605/django-foregin-key-count

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To get number of foreign elements you can do it like that:

User.objects.filter(room=my_room).count()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...