Ahmed Rabea Smaha
Ahmed Rabea Smaha

Reputation: 53

django many to one in models

in this code i want to create a new model in this new model every area from Area has more than one city from Cities

how to do that

class Area(models.Model):
    area = models.CharField(max_length=100, blank=True, null=True)

    def __str__(self):
        return str(self.area)


class Cities(models.Model):
    city = models.CharField(max_length=100, blank=True, null=True)

    def __str__(self):
        return str(self.city)

Upvotes: 0

Views: 32

Answers (1)

kobayashi
kobayashi

Reputation: 54

You can use ForeignKey for many-to-one relationships.

For exapmle, like this.

class Area(models.Model):
    area = models.CharField(max_length=100, blank=True, null=True)

    def __str__(self):
        return str(self.area)


class Cities(models.Model):
    city = models.CharField(max_length=100, blank=True, null=True)
    area = models.ForeignKey(Area, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.city)

See the django docs for detail

Upvotes: 1

Related Questions