Warm tip: This article is reproduced from stackoverflow.com, please click
django django-models

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

发布于 2020-03-31 22:58:36

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.

Questioner
Daniel Quinn
Viewed
21
Simon Dell 2020-02-03 20:30

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.