0

I'm trying to acheive catgeory and product offers in my project and am unable to come up with a solution. Like if i give offer to a category all products price in category should get the offer and for products its individual.

class Category(models.Model):
    category_name = models.CharField(max_length=15, unique=True)
    slug = models.SlugField(max_length=100, unique=True)

    class Meta:
        verbose_name_plural = "Category"


class Products(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    product_name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    description = models.TextField(max_length=500)
    price = models.IntegerField()
    images = models.ImageField(upload_to="photos/products")
    images_two = models.ImageField(upload_to="photos/products")
    images_three = models.ImageField(upload_to="photos/products")
    stock = models.IntegerField()
    is_available = models.BooleanField(default=True)
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = "Products"

    def __str__(self):
        return self.product_name

class CategoryOffer(models.Model):
    category = models.OneToOneField(Category, on_delete=models.CASCADE, related_name='cat_offer')
    valid_from = models.DateTimeField()
    valid_to = models.DateTimeField()
    discount = models.IntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(100)]
    )
    is_active = models.BooleanField(default=False)

    def __str__(self):
        return self.category.category_name

class ProductOffer(models.Model):
    product = models.OneToOneField(Products, on_delete=models.CASCADE, related_name='pro_offer')
    valid_from = models.DateTimeField()
    valid_to = models.DateTimeField()
    discount = models.IntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(100)]
    )
    is_active = models.BooleanField(default=False)

    def __str__(self):
        return self.product.product_name



So above are my models. I don't know how to implement, thought of many ways but it keeps leading to errors.

Sins97
  • 155
  • 1
  • 7

1 Answers1

0

You are using separate models for Categoryoffer and Productoffer. Make an Offer model with the following field:

class Offer:
    name = models.CharField()
    valid_from = models.DateTimeField()
    valid_to = models.DateTimeField()
    discount = models.IntegerField(
               validators=[
                   MinValueValidator(1), 
                   MaxValueValidator(100)
               ])
    is_active = models.BooleanField(default=False)

Now use the foreign key in your category and product models:

class Product:
    offer = models.ForeignKey(Offer)
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109