Проверка на отсутствие типа в условных выражениях django
выделенный текст Допустим, у нас есть две модели, как показано ниже:
class DefaultDescription(models.Model):
first_attr = models.IntegerField()
second_attr = models.CharField(max_length=20)
description = models.CharField(max_length=100)
class SomeEntity(models.Model):
first_attr = models.IntegerField()
second_attr = models.CharField(max_length=20)
# and some other unimportant attributes...
@property
def description(self):
try:
return DefaultDescription.objects.get(first_attr=self.first_attr, second_attr=self.second_attr).description
except DefaultDescription.DoesNotExist:
return ''
What I want to do is to write a single query for SomeEntity
to fetch all of the descriptions. As you can see, the description
property will run a queryset, which means a queryset for each entity. So I've tried some queryset like this:
class DescriptionAnnotationQS(models.QuerySet):
def annotate_descriptions(self):
self.annotate(
desc=models.Case(
models.When(
DefaultDescription.objects.filter(
first_attr=models.F('first_attr'),
second_attr=models.F('second_attr')).exists(),
then=models.Value(DefaultDescription.objects.get(
first_attr=models.F('first_attr'),
second_attr=models.F('second_attr')).description)),
default=models.Value('')
)
)
I used Case
and When
to check if there wasn't any default description for the entity. But still I get DoesNotExist
exception! I thought then
section will not be executed unless the condition returns True
, but apparently it'll run either way.
Есть ли способ аннотировать SomeEntity
с описанием с проверкой типа none?
P.S.: Я столкнулся с этой проблемой в унаследованном коде, которому не разрешено устанавливать отношения между его моделями.