1

我想在 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)

我怎么能做这项工作?

4

2 回答 2

3

ForeignKeydjango 中有用于这种关系的。

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().

于 2013-05-17T06:44:01.363 回答
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)
于 2013-05-17T06:44:23.623 回答