UniqueConstraint or unique_together

In models.py I have the following model:

class Intro(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    node = models.ForeignKey(Node, on_delete=models.CASCADE)
    nav_link = models.ForeignKey(NavLink, on_delete=models.CASCADE)
    headline = models.CharField(max_length=48)

    class meta:
        constraints = [
            models.UniqueConstraint(fields=['node', 'nav_link'], name='unique_intro'),

The problem is that this UniqueConstraint is being ignored when I add intros. The CREATE TABLE statement in sqlite doesn’t contain UNIQUE

CREATE TABLE "elements_intro" (
"id" char(32) NOT NULL PRIMARY KEY,
"node_id" char(32) NOT NULL REFERENCES "nodes_node" ("id") DEFERRABLE INITIALLY DEFERRED,
"nav_link_id" char(32) NOT NULL REFERENCES "headers_navlink" ("id") DEFERRABLE INITIALLY DEFERRED,
"headline" varchar(48) NULL, 

In the Django documentation I found the meta option unique_together. What’s the difference between the one I used and this one.

Kind regards,


The m in meta must be capitalized. It should be Meta

Note the first green “note” box in the docs for unique_together. The unique_together is considered obsolete and the current recommendation is to use the UniqueConstraint instead.

Hi Ken,

Ouch, I’ve been staring at my code for hours, wondering what could be wrong, didn’t notice this m.

I think I didn’t pay much attention to the green “note” box because it’s green, maybe it should be an orange “warning” box, or some other color and icon?

There are some documentation items on the site that I would perhaps like to see more strongly emphasized that way - but this particular item isn’t one of them.

This isn’t even a deprecated item yet, so it really is just a note. There’s nothing “wrong” with using it, it’s not going away in the immediate future, and it’s still being used in core Django itself. The note really is just pointing out that there’s a better way.