在django中创建OneToMany模型

时间:2013-05-17 06:39:06

标签: python django models one-to-many

我想在django中创建一对多的模型。 例如,我有

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    mobile = 1  #I want OneToMany
    website = models.URLField()

class Mobile(models.Model):
    phone_number = models.CharField(min_length=7, max_length=20)
    description = models.CharField(min_length=7, max_length=20)

我如何做这项工作?

2 个答案:

答案 0 :(得分:3)

django中有ForeignKey用于此类关系。

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    website = models.URLField()


class Mobile(models.Model):
    phone_number = models.CharField(min_length = 7, max_length = 20)
    description = models.CharField(min_length = 7, max_length = 20)
    user_profile = models.ForeignKey(UserProfile)

完成此操作后,UserProfile对象可以有多个移动电话号码,可通过userprof_obj.mobile_set RelationshipManager访问。要获取所有手机号码,您可以执行userprof_obj.mobile_set.all()

答案 1 :(得分:1)

为什么不想使用多对一关系

class Mobile(models.Model):
    user = models.ForeignKey(UserProfile)
    phone_number = models.CharField(min_length=7, max_length=20)
    description = models.CharField(min_length=7, max_length=20)