Coder949
Coder949

Reputation: 1007

How to do an "OneToMany(Field)" relationship in Django?

I know that there is no OneToManyField. But in this situation I need one.

I want to save many Image objects to one Advertisement object. How can I achieve this ?

I have the following situation:

models.py

class Image(models.Model):
   id = models.AutoField(primary_key=True)
   image = models.ImageField(upload_to="", default="", null=True)

   def __str__(self):
       return self.image.url

class Advertisement(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user', null=True)
    category = models.ForeignKey(Category, related_name='category', null=True)
    title = models.CharField(max_length=100, null=True)
    description = models.CharField(max_length=5000, null=True)
    date = models.DateTimeField(auto_now_add=True, null=True)

    def __str__(self):
        return self.description

Upvotes: 0

Views: 2353

Answers (1)

deathangel908
deathangel908

Reputation: 9699

You can use ManyToOne dependency. Have a look at official docs for more info.

class Advertisement(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user', null=True)
    category = models.ForeignKey(Category, related_name='category', null=True)
    title = models.CharField(max_length=100, null=True)
    description = models.CharField(max_length=5000, null=True)
    date = models.DateTimeField(auto_now_add=True, null=True)

    def __str__(self):
        return self.description

class Image(models.Model):
   id = models.AutoField(primary_key=True)
   image = models.ImageField(upload_to="", default="", null=True)
   advertisment = models.ForeignKey(Advertisement, related_name='advertisment', null=False)

   def __str__(self):
       return self.image.url

Upvotes: 2

Related Questions