Search code examples
pythondjangomodelsone-to-many

Create OneToMany models in django


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?


Solution

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