Reputation: 6033
I want to create one to many model in django. for example I have
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)
How I can do this work?
Upvotes: 1
Views: 717
Reputation: 53326
There is ForeignKey
in django that is used for such relationships.
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)
Once you have this, the UserProfile
object can have multiple mobile numbers which can be accessed through userprof_obj.mobile_set
which is a RelationshipManager
. To get all mobile numbers, you can do userprof_obj.mobile_set.all()
.
Upvotes: 4
Reputation: 4182
Why don't You want to use Many-To-One relationship
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)
Upvotes: 1