现在我有两个型号(未来可能更多):
class UserProfile(models.Model):
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
birth_date = models.DateField(_('birth date'), null=True, blank=True)
class TeamProfile(models.Model):
user = models.ManyToManyField(UserProfile)
name = models.CharField(_('company name'), max_length=30, blank=True)
info = models.TextField(_('information'), max_length=500, blank=True)
这两个Profiles
都应该能够选择kinds_of_sports
+ mastery
,即每个User
或Team
可以进行几种体育运动不同的掌握程度分别如:Jim(Football-> Pro,Volleyball-> Newby)。
执行以下操作是否正确:
class AbstractSports(models.Model):
KINDS_OF_SPORTS = (
(1, _('football')),
(2, _('volleyball')),
(3, _('hockey')),
)
MASTERY_CHOICES = (
(1, _('newby')),
(2, _('amateur')),
(3, _('semi-pro')),
(4, _('pro'))
)
kind_of_sport = models.IntegerField(_('kind of sport'), null=True, blank=True, choices=KINDS_OF_SPORTS)
mastery = models.IntegerField(_('mastery'), null=True, blank=True, choices=MASTERY_CHOICES)
class Meta:
abstract=True
class UserSports(AbstractSports):
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
class TeamSports(AbstractSports):
team = models.ForeignKey(TeamProfile, on_delete=models.CASCADE)
还是会有更好的方式?
答案 0 :(得分:1)
我会对此进行一次尝试,我不确定这是多少改进,但是当我正在阅读你的问题时,它开始贯穿我的脑袋。
我不确定团队和用户配置文件的差异或相似之处,但您可能希望将其转换为单个模型,然后使用一种类型来定义其用户或团队。如果您想要一个分配了用户配置文件的团队,那么就与自己建立关系。
class Profile(models.Model):
PROFILE_TYPES = (
('USER', 'User'),
('TEAM', 'Team'),
)
type = models.CharField(max_length=4, choices=PROFILE_TYPES)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
birth_date = models.DateField(_('birth date'), null=True, blank=True)
user = models.ManyToManyField('Profile') #manytomany itself for teams that have profiles assigned to it
name = models.CharField(_('company name'), max_length=30, blank=True)
info = models.TextField(_('information'), max_length=500, blank=True)
然后只需要一个像你一样的单一运动模型,然后再回到个人资料中
class Sports(models.Model):
KINDS_OF_SPORTS = (
(1, _('football')),
(2, _('volleyball')),
(3, _('hockey')),
)
MASTERY_CHOICES = (
(1, _('newby')),
(2, _('amateur')),
(3, _('semi-pro')),
(4, _('pro'))
)
kind_of_sport = models.IntegerField(_('kind of sport'), null=True, blank=True, choices=KINDS_OF_SPORTS)
mastery = models.IntegerField(_('mastery'), null=True, blank=True, choices=MASTERY_CHOICES)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)