M
M
maxclax2015-03-15 02:26:51
Django
maxclax, 2015-03-15 02:26:51

How to get validated in DJANGO?

class Course(models.Model):
    objects = CourseManager()

    class Meta:
        ordering = ('ccy',)
        verbose_name = _('course.model.verbose_name')
        verbose_name_plural = _('course.model.verbose_name_plural')
        unique_together = ('ccy', 'base_ccy')


    def __str__(self):
        return str(self.ccy.code) + '/' + str(self.base_ccy.code)

    # первая валюта
    ccy = models.ForeignKey(Currency, verbose_name=_('course.model.ccy'), related_name="ccy")

    # вторая валюта
    base_ccy = models.ForeignKey(Currency, verbose_name=_('course.model.base_ccy'), related_name="base_ccy")

    # покупаем
    buy = models.DecimalField(verbose_name=_('course.model.buy'), max_digits=20, decimal_places=10, default=0)

    # продаем
    sale = models.DecimalField(verbose_name=_('course.model.buy'), max_digits=20, decimal_places=10, default=0)

    # время последнего обновления
    updated_at = models.DateTimeField(auto_now=True)

    def clean(self):
        if Course.objects.get(ccy=self.base_ccy, base_ccy=self.ccy):
            raise ValidationError('Уже есть обратное направление!')

I have the above model. The model has one uniqueness condition when saving by two fields unique_together = ('ccy', 'base_ccy') and additionally, a check on the reverse direction of fields has been added in the clean method. I ran into a problem when saving Course matching query does not exist correctly, and when it is incorrect, the clean method works. Tell me how to get around this problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Klimenko, 2015-03-15
@aklim007

If the only information you need is whether such an entry exists in the database, then there is a special method for this: exists
djbook.ru/rel1.7/ref/models/querysets.html#django....

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question