@Boldy

Как создать кастомное поле в django?

Есть два класса, в каждом из которых есть поле, которое имеет одинаковые choices, валидаторы и название для форм но разные названия столбцов в таблице в БД:
class MyField(models.CharField):
    def __init__(self):
        self.choices = (
            (1, "choice1"),
            (2, "choice2")
        )
    self.verbose_name = "Das ist mein field"
    self.validators = [MaxLengthValidator(1), ]
class A(models.Model)
    a_field = MyField()

class B(models.Model)
    b_field = MyField()


Как реализовать подобную штуку?
  • Вопрос задан
  • 206 просмотров
Решения вопроса 1
@Boldy Автор вопроса
Комментировать
Пригласить эксперта
Ответы на вопрос 2
sim3x
@sim3x
The Zen of Python

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
Ответ написан
Комментировать
@deliro
Это шутка такая или какой-то трюк? Зачем нужно создавать отдельный класс, если можно написать просто
CHOICES = (
    (1, "choice1"),
    (2, "choice2")
)

class A(models.Model):
    a_field = models.SmallIntegerField(choices=CHOICES)

class B(models.Model):
    b_field = models.SmallIntegerField(choices=CHOICES)
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы