'Django add multiple Users to lobby model
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
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Lzak |