Daniel Quinn
Daniel Quinn

Reputation: 6418

Django: child models with the same properties, but different attributes on those properties

I have two models in my database that, if I don't do anything "creative" will look something like this:

class AbstractModel(models.Model):

    uuid = models.UUIDField(default=uuid.uuid4)

    class Meta:
        abstract = True


class ModelA(AbstractModel):
    name = models.CharField(max_length=128)


class ModelB(AbstractModel):
    name = models.CharField(max_length=128, blank=True, null=True)

The only real difference between ModelA and ModelB is that I want ModelA's name property to be non-nullable, but writing it like this, especially when you consider that I've got about 10 different fields to write in much the same situation, feels very not-DRY. Surely, there's a better/smarter way?

Note that this isn't about validation, so moving the blank-checking up into a form isn't going to solve the problem. I want the database column to be NOT NULL for ModelA and NULL for ModelB.

Upvotes: 0

Views: 51

Answers (1)

Simon Dell
Simon Dell

Reputation: 638

ModelA and ModelB probably represent entities which don't have as much in common as it appears when you list their properties. The fact that one needs values just to live and the other doesn't suggests their behavior and responsibilities require independant representation. They do different things for you.

Upvotes: 1

Related Questions