A
A
Alex Xmel2021-06-28 14:23:15
Django
Alex Xmel, 2021-06-28 14:23:15

How to select all choices in the model to pass them to the template?

There is a simple model that has a field for selecting the transaction status:

class ModelDeal(models.Model):
    STATUS_CHOISES = (
        ('ok', 'Выполнена'),
        ('new', 'Новая заявка'),
        ('cancel', 'Отменена'),
        ('error', 'Ошибка'),
        ('timesup', 'Время вышло'),
    )
    deal_status = models.CharField('Статус', max_length=50, choices=STATUS_CHOISES, default='new')


I need to pass all possible STATUS_CHOISES in html template.
Previously, I did this: temp=ModelDeal.objects.all() and then compiled the list I needed from these enumerations, but earlier I had such a model set once during creation and was not particularly changeable. And now I have this choises in the main model, which is actively used and getting all the records to collect all the choises is kind of stupid. In theory, I should be able to get them all even from an empty model. How can I do it ?
ps I understand that all choises can be put into a separate model and the issue can be resolved, but this is not the way I need now

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Nesterov, 2021-06-28
@Desead

There are two options:

# Вызвать напрямую
var = ModelDeal.STATUS_CHOISES 
# Создать метод класса
@classmethod
    def return_choises(cls):
        return cls.STATUS_CHOISES 
***
var = ModelDeal.return_choises()

In both the first and second cases, a tuple will be returned that you can work with.
The second option, in my opinion, is better, because in the method you can process the data before returning it (convert it to a dictionary, etc.)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question