python - 在 Django 中创建 OneToMany 模型

标签 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)

我怎样才能完成这项工作?

最佳答案

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/

相关文章:

Python3 deepcopy 类实例不起作用

html - {% extends "base.html"%} 未连接静态

django - 以编程方式保存 ImageField 会复制图像文件

python - Pandas :read_csv 表示 'space-delimited'

Python 请求获取一个应该正常工作的 URL 的错误页面

python - 如何进行十六进制增量?

python - 无法在我的 Django 项目中使用 Sphinx 生成 autodoc

django - Django Fixtures 如何处理 ManyToManyFields?

django 外键保存

Django 管理站点,更改不同用户的模型可见性