Home > Net >  Django: Override inherited field options
Django: Override inherited field options

Time:10-14

I am working with Django 3.2 and I would like to create an abstract class with 2 fields whose default values (or their blank attribute) could change in each of the child classes.

I'd like not to override the full fields but only the options that change. That way, if I decide to make the icon field unique in the future, I should only change the parent abstract class and not all the child models.

# behaviors.py

from django.db import models
from colorfield.fields import ColorField


class Representable(models.Model):
    color = ColorField(_("color in the app"), blank=True)
    icon = models.CharField(_("icon in the app"), max_length=50, blank=True)

    class Meta:
        abstract = True
# models.py

from django.db import models
from .behaviors import Representable


class Item(Representable, models.Model):
    name = models.CharField(_("name"), max_length=50, blank=False)
    # color couldn't be blank
    # icon couldn't be blank    

    class Meta:
        verbose_name = _("item")
        verbose_name_plural = _("items")


class Tag(Representable, models.Model):
    name = models.CharField(_("name"), max_length=200, blank=False, unique=True)
    # color default value shoud be #00AEC7 (but could be blank)
    # icon default value shoud be mdi-label (but could be blank)    

    class Meta:
        verbose_name = _("tag")
        verbose_name_plural = _("tags")

Any ideas?

CodePudding user response:

You can override fields in subclasses of abstract models and set whatever attributes you want

class Tag(Representable):
    ...
    color = ColorField(_("color in the app"), blank=True, default='#00AEC7')
    icon = models.CharField(_("icon in the app"), max_length=50, blank=True, default='mdi-label')

CodePudding user response:

Not an expert but this can work:

from django.db import models
from .behaviors import Representable


class Item(Representable):
    name = models.CharField(_("name"), max_length=50, blank=False, null=True)
    color = ColorField(_("color in the app"), blank=False)
    icon = models.CharField(_("icon in the app"), max_length=50, blank=False)   

    class Meta:
        verbose_name = _("item")
        verbose_name_plural = _("items")


class Tag(Representable):
    name = models.CharField(_("name"), max_length=200, blank=False, unique=True)
    color = ColorField(_("color in the app"), blank=True,null=True, default='#00AEC7')
    icon = models.CharField(_("icon in the app"), max_length=50, blank=True, null=True, default='mdi-label')   

    class Meta:
        verbose_name = _("tag")
        verbose_name_plural = _("tags")

  • Related