Unique field value Django model

Viewed 157

So, i have two models: RetailStore and Product. Product contains a ForeignKey to RetailStore and a field named sku. Basically what i need is to make sure that the sku field is unique into a store, but not between all stores, e.g:

Store1: Product(sku="sku1"), Product(sku="sku2"), Product(sku="sku3"), Product(sku="sku1") <- can't have this last one because it already exists.

Store2: Product(sku="sku1"), Product(sku="sku2"), Product(sku="sku3") <- This is ok

Store3: [...] <- Same goes for others Store.

My Models

class RetailStore(StandardModelMixin):
    cnpj = models.CharField(
        blank=False, null=False, unique=True, max_length=200, validators=[validate_cnpj], verbose_name="CNPJ"
    )

    [other fields...]

class Product(StandardModelMixin, SoftDeletionModel):
    sku = models.CharField(blank=False, null=False, max_length=200, verbose_name="SKU")
    
    [other fields...]
    
    retail_store = models.ForeignKey(
        RetailStore,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        related_name="products",
        verbose_name="Retail Store",
    )
2 Answers

You can use UniqueConstraint so you can have the same SKUs in different stores, but not in one.

class Product(StandardModelMixin, SoftDeletionModel):
    ...
    
    class Meta:
        constraints = [models.UniqueConstraint(
            fields=['sku', 'retail_store'], 
            name='unique_sku_in_store'
        )]
Related