Home > Blockchain >  Django add multiple Users to lobby model
Django add multiple Users to lobby model

Time:02-12

I want to add Users to my players field in the lobby but i dont know how. Every user should be in just one lobby.

User Model

class GeoUser(AbstractUser):
        user_score = models.IntegerField(default=0)
        email = models.EmailField(unique=True)

Lobby Model

class Lobby(models.Model):
    lobby_code = models.CharField(
        max_length=18, unique=True)
    
    players = # here i want to add multiple users that should be in the lobby

Thanks in advance

CodePudding user response:

I would advice you to add ForeignKey in GeoUser model pointing to Lobby model. This is OneToMany relation for Lobby, because one GeoUser will be in one Lobby, but there is actually no limit on how many GeoUser objects can be in Lobby.

class GeoUser(AbstractUser):
    user_score = models.IntegerField(default=0)
    email = models.EmailField(unique=True)

    lobby = models.ForeignKey('Lobby', on_delete=models.SET_NULL, null=True, default=None, related_name='users')

class Lobby(models.Model):
    lobby_code = models.CharField(
        max_length=18, unique=True)
    
    def players(self):
        return self.users.all()

To get all players just call:

lobby = Lobby.objects.first()
lobby.players()    # returns a QuerySet of all related GeoUser objects

CodePudding user response:

I believe what you're looking for is the ManyToManyField, which you would implement by:

players = models.ManyToManyField(GeoUser)

You do have the constraint that a user should be part of a maximum of 1 lobby. I guess you could technically iterate over all of the lobbies every time and check if the user is currently in any lobby. If you plan to have a lot of lobbies, then it would probably make sense to save the user's lobby in the User model.

In my opinion, it's much better to create separate model responsible for maintaining the relation between the user and the lobby (see Django documentation for the through parameter). Now you would be able to enforce uniqueness using UniqueConstraint and also save other metadata such as the timestamp of when they joined.

  • Related