我正在使用 Django 3.2,我想創建一個包含 2 個欄位的抽象類,其默認值(或它們的空白屬性)可以在每個子類中更改。
我不想覆寫完整的欄位,而只想覆寫更改的選項。這樣,如果我決定將來使 icon 欄位唯一,我應該只更改父抽象類而不是所有子模型。
# 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")
有任何想法嗎?
uj5u.com熱心網友回復:
您可以覆寫抽象模型子類中的欄位并設定您想要的任何屬性
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')
uj5u.com熱心網友回復:
不是專家,但這可以作業:
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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/310972.html
標籤:Python 姜戈 哎呀 遗产 django-models
上一篇:查找字串中重復單詞旁邊的字母
