R
R
Ronii2016-01-26 07:06:42
Django
Ronii, 2016-01-26 07:06:42

How to refer to own constant when creating a class?

When creating a class, it is not possible to refer to the own constant Tag.TYPE_KEYWORD, because the class has not yet been created.
Are there any solutions other than putting a number on the last line right away?

class Tag(models.Model):
    TYPE_KEYWORD = '1'
    TYPE_TOPIC = '2'
    
    type = models.IntegerField(default=Tag.TYPE_KEYWORD)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
marazmiki, 2016-01-26
@Ronii

class Tag(models.Model):
    TYPE_KEYWORD = '1'
    TYPE_TOPIC = '2'
    
    type = models.IntegerField(default=TYPE_KEYWORD)

B
bromzh, 2016-01-26
@bromzh

class Foo:
    class Meta:
        TYPE_KEYWORD = '1'

    tp = Meta.TYPE_KEYWORD

# или
class Bar:
    foo = 3
    bar = {'key': 'value', 2: foo}
    baz = bar[2]
    qux = bar['key']

Maybe it will work somehow. In general, classes that extend models.Model are created using the magic of metaclasses, and it’s possible that it won’t work anyway. When creating regular classes, everything works without crutches.

Z
zelsky, 2016-01-26
@zelsky

Create a file constants.py inside the application, write constants there and connect it to the model or view.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question