我有一个抽象的产品模型,我希望它能够容纳多个图像,因此我决定制作另一个图像模型并具有一个Product的ForeignKey,但是我很快意识到这是不可能的。我决定选择抽象基本模型的原因是性能提高,因为每个子模型都在自己的表中。每个子类都有一个不同的Image模型,这听起来很糟糕,因为将会有20多个子类。
class Product(models.Model):
title = models.CharField(max_length=50)
description = models.CharField(max_length=50)
category = models.ForeignKey('Category', on_delete=models.CASCADE, blank=False)
class Meta:
abstract = True
class Book(Product):
author = models.CharField(max_length=50)
publisher = models.CharField(max_length=50)
class Shoes(Product):
colour = models.CharField(max_length=50)
size = models.CharField(max_length=50)
class Image(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images')
image = models.ImageField(upload_to=get_image_path, blank=True, null=True)
我该如何解决这个问题?
答案 0 :(得分:1)
您可以使用ManyToManyField
:
class Product(models.Model):
title = models.CharField(max_length=50)
description = models.CharField(max_length=50)
category = models.ForeignKey('Category', on_delete=models.CASCADE, blank=False)
images = models.ManyToManyField(Image)
class Meta:
abstract = True
插入数据
b1 = Book.objects.create(...) #can't include M2M yet
i1 = Image.objects.create(...)
i2 = Image.objects.create(...)
b1.images.add(i1, i2)
您可以像这样查询图像:
books = Book.objects.all().prefetch_related('images')
images_for_book_1 = books[0].images.all()