我想在 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)
我怎样才能完成这项工作?
最佳答案
有ForeignKey
在用于此类关系的 django 中。
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()
。
关于python - 在 Django 中创建 OneToMany 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16602969/