I’m making an ecommerce app that primarily sells audiobooks. These will always be available to stream (but not download) from the website. The catch here is there also need to be a dynamic amount of variations for each product.
For example, I have this Product
model:
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="product_creator")
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
sku = models.CharField(max_length=255, null=True, blank=True)
title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
description = models.TextField(blank=True)
slug = models.SlugField(max_length=150)
price = models.DecimalField(max_digits=4, decimal_places=2)
audio_file = models.FileField(upload_to="audiobooks/")
cover_image = models.ImageField(upload_to="covers/", blank=True, null=True)
published_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.title
And since I need to have the ability to create a new variation for the product, I can also have a Variation
model like this:
class Variation(models.Model):
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
description = models.TextField(blank=True)
price_increase = models.DecimalField(max_digits=4, decimal_places=2)
is_downloadable = models.BooleanField(default=False)
downloadable_file = models.FileField(upload_to="audiobooks/downloadable/", blank=True, null=True)
variation_image = models.ImageField(upload_to="audiobooks/images/", blank=True, null=True)
def __str__(self) -> str:
return self.name
Let’s say I create some audiobook products with Product. I want all the products to have variations that include a downloadable .mp3 file, and a downloadable .m4b file. Some of them will have physical CDs, some of them may have accompanying comic books, and some may have unique collector items like an edition of the comic book with a gold cover, or a book with black pages and white text. I can create all these variations with Variation model, but I can’t figure out how to connect any number of these variations with a product efficiently. I was thinking a new table that holds a foreign key to the product and then somehow a variable number of FKs to the variations, but is that even possible, or practical at all?