gpt4 book ai didi

python - 在 Django 中创建 OneToMany 模型

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:06 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com