2

I am wondering since ages how to achieve the following:

I have an abstract class wrapping several attributes shared by multiple models. But not every model needs every attribute in exactly the same way.

Here is an example: MyModelA and MyModelB both have two fields: value_1 and value_2. But while MyModelA needs them to be required/not nullable, they can be nullable for MyModelB.

class MyAbstractModel(models.Model):
    value_1 = models.IntegerField()
    value_2 = models.IntegerField()

    class Meta:
         abstract = True

What I tried:

  1. Not deriving MyAbstractModel from models.Model but from object like a regular mixin

  2. Setting a class attribute which is overwritten in the child classes to determine the nullable-state. It always takes the definition from MyAbstractModel.

  3. Using a class attribute but not set it in the MyAbstractModel. Then the makemigrations command fails because of the undefined variable.

  4. Cry

Being DRY is such an important paradigm in django, I really wonder that there is nothing on this topic in the internet.

Thanks in advance!

Ron
  • 22,128
  • 31
  • 108
  • 206
  • Seems reasonable to me, but, I wouldn't include fields that aren't ***"identical"*** in the base model – JPG Jan 06 '21 at 11:10
  • think of using `Model mixins` https://www.ianlewis.org/en/mixins-and-python – cizario Jan 06 '21 at 11:16
  • @cizario Wont work for model fields! They are not detected and therefore never are persisted in the database :( – Ron Jan 06 '21 at 11:19
  • @JPG Sorry, didnt get your point. What do you mean by that? – Ron Jan 06 '21 at 11:19
  • @Ron can you explain that ? mixins are simply python classes, refer to this https://stackoverflow.com/a/25817237/12368419, i used model mixins in my projects without any problems (migrations are created as it should be, and the database is created) – cizario Jan 06 '21 at 11:31
  • That is `value_1 = models.IntegerField()` is not same as `value_1 = models.IntegerField(null=True)` (in Django as well as in DB). So, I would redefine them in my subclasses as per my requiremernt – JPG Jan 06 '21 at 11:35
  • @cizario Thats interesting, found some articles in the net describing exactly my behavior! Just give it a shot, maybe it worked on older django versions? – Ron Jan 06 '21 at 12:05
  • @JPG True, but still not DRY. Thats why I asked the question :( – Ron Jan 06 '21 at 12:05
  • Imho, you dont have to think about dry here – JPG Jan 06 '21 at 12:12
  • it seems this way :) – Ron Jan 06 '21 at 14:11

0 Answers0