1👍
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
0👍
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.
- [Answered ]-Only allow leaf category as a choice – Django
- [Answered ]-ValueError when getting objects by id
- [Answered ]-Pass amount from Stripe checkout for to view function in Django
- [Answered ]-Override Template django-allaut