具有关系的 django 模型的最佳模式

the best schema for a django model with relation

我有一个模型用户和一个模型团队。 我经常使用团队的所有字段和用户的一个字段(用户名),但并非总是如此!

一个团队包含很多用户,为了这些关系我创建了这个模型(1):

class joinTeam(models.Model):
    username_user=models.CharField(max_length=30)
    team = models.ForeignKey(Projet, null=False)

但我犹豫要用这个 (2) 替换这个字段 'username_user':

 class joinTeam(models.Model):
    username_user=models.ForeignKey(User, null=False)
    team = models.ForeignKey(Projet, null=False)

I'm afraid that this model (2) consumes more capacity the the first (1). 

如何使用简单的 CharField 或 ForeignKey?

I'm afraid that this model (2) consumes more capacity the the first (1).

别害怕,django 只会存储对用户的引用 (pointer/id),而不是整个模型实例。

您的模型应该如下所示:

class joinTeam(models.Model):
    user=models.ForeignKey(User, null=False)
    team = models.ForeignKey(Projet, null=False)

username_user 重命名为 user

此外,尽量不要重复数据是一种很好的做法,如果您将 username 存储在 joinTeam table 中,那么您正在重复数据,因为您可以从 user table 中获取它。

更喜欢使用带有外键的示例二。

best practices, rename the user_name_user to user
and by default, null = False, but if you wants, can explicit it

class joinTeam(models.Model):
    user = models.ForeignKey(User)
    team = models.ForeignKey(Projet)

查询的时候,直接用select_related,数据库就命中了

joinTeam.objects.all().select_related('user')