我知道没有OneToManyField。但在这种情况下我需要一个。
我想将许多Image对象保存到一个Advertisement对象中。我怎样才能做到这一点?
我有以下情况:
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
答案 0 :(得分:1)
您可以使用ManyToOne
依赖项。有关详细信息,请查看官方docs。
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