dc115
dc115

Reputation: 137

Enforce field uniqueness to parent in many-to-one relation

I have a Table model which is many-to-one with a Restaurant model. Is there a way to have a field reference_label in the Table model that must be unique per restaurant, but not across different restaurants?

In short, I want to enforce reference_label uniqueness for tables with the same foreign key.

I know I can just use the Table's id, but I want each restaurant to be able to customize how they label their tables.

Upvotes: 2

Views: 291

Answers (2)

Stevy
Stevy

Reputation: 3387

If you are using Django 2.2 you can use UniqueConstraint instead of unique_together like this:

class Meta:
    constraints = [
        models.UniqueConstraint(fields=['restaurant', 'reference_label'], name='give_it_some_name')
    ]

As the docs state:

Use UniqueConstraint with the constraints option instead.

UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future.

Upvotes: 3

Selcuk
Selcuk

Reputation: 59184

You can use unique_together:

class Restaurant(models.Model):
    ...

class Table(models.Model):
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    reference_label = models.CharField(max_length=20)
    ...
    class Meta:
        unique_together = ['restaurant', 'reference_label']

Upvotes: 1

Related Questions