python - Implementing a model for "teams" in django -
i want implement team feature in django 1.8. (team in sports team)
every user can join 1 team @ time , team can hold many users. unsure how define models.py
i started core, unsure how make connection of team<->user
from django.db import models class team(models.model): name = models.charfield(max_length=64, unique=true) description = models.textfield(max_length=1024) logo = models.imagefield() django.contrib.auth.models import user class player(models.model): user = models.onetoonefield(user) team = foreignkey('team')
do create second class user_team or add team foreign key user? (and if thats way need this?)
thanks,
wegi
// edit: added code @ bottom. player model enough define relationship?
for use case, still suggest alternative using manytomany field, intermediate model , model manager.
a quick sample structure looks this:
from django.db import models django.contrib.auth.models import user class team(models.model): name = models.charfield(max_length=64, unique=true) description = models.textfield(max_length=1024) logo = models.imagefield() players = models.manytomanyfield(user, through='player') class playermanager(models.manager): use_for_related_fields = true def add_player(self, user, team): # ... code here ... def remove_player(self, user, team): # ... code here ... def trasnfer_player(self, user, team): # ... code here ... class player(model.model): user = models.foreignkey(user) team = models.foreignkey(team) other_fields = #... objects = playermanager()
usage:
player.objects.add_player(user, team, *other_fields)
you able user related team, example:
team_with_user = team.objects.filter(players__name="hello") user_in_team = user.objects.filter(team__name="world")
note: haven't tested code, please correct me if make mistake above.
the reason why prefer way abstract away database logic application. in future if there need allowing user
joining multiple teams, can change application logic allow through manager.
Comments
Post a Comment