2825 explained code solutions for 75 technologies


djangoHow to make two fields unique together


class Product(models.Model):
    product_name = models.CharField(max_length=100)
    shop = models.CharField(max_length=100)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["product_name", "shop"],
                name="unique_product_name_for_shop",
            ),
        ]ctrl + c
constraints

where you should write all of your constraints of your model

models.UniqueConstraint

constraint that make two fields unique

fields=["name", "shop"]

fields that you want them to be unique together

name

unique name for this constraint