slawek
slawek

Reputation: 1

Django model + Unique column on two tables (inheritance)

How to create constraint (on database to keep integrity) base on columns from child and parent table?

Model:

class DBMaster(models.Model):
        col1 = models.CharField()

 class DBOne(DBMaster):
        col_own....
        col1 - should be this same how in DBMaster

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['col_own', 'col1'], name='CON_UNIQUE_1')
        ]

We can use materialized view but we wont. Any sugestions?

Upvotes: 0

Views: 137

Answers (1)

Nikita Davydov
Nikita Davydov

Reputation: 957

I think you should use unique_together in your model and your base model should be abstract

 class BaseDBMaster(models.Model):
    col1 = models.CharField()

    class Meta:
        abstract = True

 class DBMaster(BaseDBMaster):
     pass

 class DBOne(BaseDBMaster):
    col_own....
    col1 - should be this same how in DBMaster

    class Meta:
        unique_together = ('col1', 'col_own')

Upvotes: 3

Related Questions