0

I have 4 models: company, store, product and stock. The stock model has 3 ForeignKey to the other models and I need that the same product can only be inserted once in a company's store when a stock is created.

Models:

class Company(models.Model):
    owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name='company')
    name = models.CharField(max_length=150, unique=True, null=False)
    type_choices = [('Retailer', 'Retailer'), ('Provider', 'Provider')]
    type = models.CharField(choices=type_choices, max_length=12, null=False)
    dropshipping = models.BooleanField(default=False)
    city = models.CharField(max_length=24, null=False)
    postal_code = models.IntegerField(null=False)
    address = models.CharField(max_length=256, null=False)
    phone = models.CharField(max_length=24, null=False)
    is_active = models.BooleanField(default=False)
    date_created = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.name

class Store(models.Model):
    location = models.CharField(max_length=100, null=False)
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='store_owner')

    def __str__(self):
        return self.location

class Product(models.Model):
    name = models.CharField(max_length=256, unique=True, null=False)
    brand = models.CharField(max_length=128, null=False)
    date_added = models.DateTimeField(default=timezone.now)
    image = models.ImageField(upload_to = 'static/img/')

    def __str__(self):
        return self.name

class Stock(models.Model):
    price = models.DecimalField(max_digits=8, decimal_places=2, null=False)
    quantity = models.IntegerField(null=False)
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_stock')
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='company_stock')
    store = models.ForeignKey(Store, on_delete=models.CASCADE, related_name='store_stock')

How can I achieve this?

Akond
  • 9
  • 4
  • "Store" is already related to "Company". So don't need ForeignKey for both in "Stock" model. – sandeep Nov 28 '19 at 12:08
  • See https://stackoverflow.com/questions/2201598/how-to-define-two-fields-unique-as-couple on how to group columns together so that their combination is unique. This way you can still have a unique primary key field within your model which will probably come in very handy. – anowlinorbit Nov 28 '19 at 12:10

1 Answers1

0

Perfect, it worked with

class Meta:
    unique_together = ('product', 'store')

on stock model

Akond
  • 9
  • 4