Class Employee(models.Model):
name = models.CharField(max_length=100)
age = models.CharField(max_length=100)
salary = models.CharField(max_length=100)
I need to write a queryset to fetch all the details with an additional field called Group. So Group will set "A" if salary is grater than 10000 else "B".
CodePudding user response:
Seems like a job for Case/When https://docs.djangoproject.com/en/4.0/ref/models/conditional-expressions/#case
Try something like:
Employee.objects.annotate(
group=Case(
When(salary__gte=10000, then=Value('A')),
default=Value('B'),
),
CodePudding user response:
You can do it in model class as property:
@property
def group(self):
if self.salary > 10000:
return 'A'
else:
return 'B'