B
B
Boldy2015-07-25 17:11:03
Django
Boldy, 2015-07-25 17:11:03

How to create a custom field in django?

There are two classes, each of which has a field that has the same choices, validators and form name but different column names in a table in the database:

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()

How to implement something like this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sim3x, 2015-07-25
@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!

R
Roman Kitaev, 2015-07-25
@deliro

Is this a joke or some kind of trick? Why do you need to create a separate class when you can just write

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)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question