M
M
maxclax2014-12-27 10:17:54
Django
maxclax, 2014-12-27 10:17:54

Output data depending on is_active, Django-admin?

I have two models. First

class Currency(models.Model):

    # код валюты, пример UAH
    code = models.CharField(_('code'), max_length=3, unique=True)

    # название валюты, пример Украинская гривна
    name = models.CharField(_('name'), max_length=35, unique=True)

    # символ валюты, пример $
    symbol = models.CharField(_('symbol'), max_length=4, blank=True)

    # активность валюты
    is_active = models.BooleanField(_('active'), default=True, help_text=_('The currency will be available.'))

Second:
class Сourse(models.Model):
   
    # входящая валюта
    currency_from = models.ForeignKey(Currency, verbose_name=_('_from'), related_name="currency_from")

    # исходящая валюта
    currency_to = models.ForeignKey(Currency, verbose_name=_('_to'), related_name="currency_to")

    # по курсу 1 к:
    course = models.DecimalField(verbose_name=_('course'), max_digits=20, decimal_places=10,
                                 help_text="Курс по текущей паре")

There are more than 100 records in the Currency model, but only 5 of them are active (is_active), when the second model is filled in the lists, all records from the first model are available for selection. How to limit the selection by active records from the first model? Removing the excess from it is not an option :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey K, 2014-12-27
@maxclax

Through the form:

class CourseForm(forms.ModelForm):
    currency_from = forms.ModelChoiceField(queryset=Currency.objects.filter(is_active=True))

O
Oscar Django, 2014-12-27
@winordie

You can create your own manager

# First, define the Manager subclass.
class ActiveCurrency(models.Manager):
    def get_queryset(self):
        return super(ActiveCurrency, self).get_queryset().filter(is_active=True)


class Currency(models.Model):
    ...

    objects = models.Manager() # The default manager.
    active_currency = ActiveCurrency() # The Active-specific manager.

And then where it is necessary to use it instead of the standard one.
Currency.objects.all() == более 100 записей
Currency.active_currency.all() == 5

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question