mcgruff14
mcgruff14

Reputation: 338

Django Model Unique Constraint Exception

I have a django model that has a unique together constraint, but I need a specific instance to be able to be repeated over and over. Is this possible?

name = models.ForeignKey(name)
time = models.BigIntegerField()

class Meta:
    unique_together = ("name", "time",)

I'm trying to get time=0 and for the same user multiple times. However, in every other instance it time needs to be unique.

Upvotes: 1

Views: 1262

Answers (1)

Vingtoft
Vingtoft

Reputation: 14586

A unique_together field is validated on database level (see documentation). It is therefore not possible to make exceptions.

A solution could be to set time = null instead of time = 0. Your database backend needs to support unique constraint that allows empty values (see this post). This is supported by most major DBMS, but not all.

If you database does not support it you'll have to write a custom form validation.

Upvotes: 2

Related Questions